简体   繁体   中英

Return `void` from `async` funtion

So I ran into this a few times now and I've always just ignored it.

In TypeScript when I code:

async function someAsyncFunc(): void {
    const prom = await somePromise();
}

It complains to me that async function should always have the return type of: Promise<T> . So what it wants from me is:

async function someAsyncFunc(): Promise<void>

I know that, but this method does not return anything . Up to this point, I've just always given in, and used the type Promise<void> but this will lead to bugs as TypeScript now thinks this function returns a promise, won't it?

Had an idea whilst writing this question and tested it.. turned out to be true. Check out my own answer in case your wondering :)

Error message so it will hopefully be index by google:

The return type of an async function or method must be the global Promise<T> type.

An async function is consider an extension of the Promise paradigm .

For javascript/typescript know that the return of a specific function is asynchronous is because it return a Promise . This means that the return type of an ansynchronous function is always Promise . Then, you can wrap a value into that promise which can be void , number , string , another promise , etc.

From MDN :

An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result .

More over:

An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value. Remember, the await keyword is only valid inside async functions.

Resuming: The aysnc/await in functions are syntax sugar to facilitate the code readability.

Async functions will always return a promise. The result of your answer to your question should print Promise{<state>: "<finished>"} instead of void. You need to await the async function to see the void response

async function test() {};
console.log(test());

becomes

async function test() {};
console.log(await test());

Whist writing this question the solution came to my mind. So now I'm answering this myself in case anyone else is wondering.

When you create an async function JavaScript implicitly returns a Promise (which then will be void). Much like if you're writing a normal void function you don't have to put return; at the end, it just does return.

 async function test() {}; // Will return a resolved void promise // the code snipped result only shows "{}" check it out in // the browser console and you'll see console.log(test());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM