Reputation: 1793
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).
Upvotes: 0
Views: 1351
Reputation: 136239
Your understanding is correct!
Is the
interfaceFunction
explicitly required to be declared asasync
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.
Upvotes: 2
Reputation: 1375
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));
Upvotes: 1