Home > Software design >  Correct Usage of Async in Typescript
Correct Usage of Async in Typescript

Time:01-27

What is the correct usage of the async keyword in typescript? My understanding is that it is to only allow the usage of await in a function body. Specifically,

async returnPromise() : Promise<any> {} 

export const interfaceFunction() = async () {
    return returnPromise();
}

// Usage in another module
const returnValue = await interfaceFunction();

Is the interfaceFunction explicitly required to be declared as async in this case? The code works with or without the async keyword (and the return type remains a Promise in both the cases as well).

CodePudding user response:

Your understanding is correct!

Is the interfaceFunction explicitly required to be declared as async in this case?

No. If you simply return a Promise you dont need to mark the method as async. Ony mark a method async if you want to await something within it.

CodePudding user response:

I'm not pretending for a full answer.

but another option that async guarantee that function returns a promise, and make result than'able. It helps much when only part of function is awaitable. see example below.

function nPromice(){
    return Promise.resolve(2);
}
async function  n(){
    if(Math.random() > 0.5 ){
        return await nPromice(); 
    } else {
        return 1;
    }
}
n().then(x => console.log(x));

Playground Link

  •  Tags:  
  • Related