0

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).

1
  • It is a syntatic sugar of Promise. You don't need to declare async if your function return a Promise. You can directly await a Promise just like await an async function. If you declare your function async, you shouldn't return a Promise, otherwise you have to await twice. You should return await returnPromise(); if you really need to use a Promise from other source. Commented Jan 27, 2022 at 5:50

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.