简体   繁体   中英

JavaScript async function, when is returned promise resolved in the case of no return value

This question is regarding the async/await proposal. As I understand it the following function:

async function foo() {
   return await someAsyncFn();
   await performSomeOtherAsyncAction();
   doOneLastThing();
}

returns as soon as the someAsyncFn() resolves.

However, what if there is no return value:

async function() {
       await someAsyncFn();
       await performSomeOtherAsyncAction();
       doOneLastThing();
}

Does the returned promise resolve immediately after exiting the function similar to this:

function foo() {
    someAsyncFn()
        .then(() => {
            return performSomeOtherAsyncAction();
        })
        .then(() => {
            doOneLastThing();
        });
}

or does it wait until the inner promise has resolved as well like this:

function foo() {
    return someAsyncFn()
        .then(() => {
            return performSomeOtherAsyncAction();
        })
        .then(() => {
            doOneLastThing();
        });
}

async/await lets you write asynchronous processes in a synchronous "style". It works exactly like you'd expect a synchronous function to work, except that it returns a promise. In other words, it will behave as in your last example. It executes all the statements and returns a promise that resolves to undefined .

I would say that base on the Specification the Async/await command it's only wrapping the promise/process and expecting for the resolve/reject call to return the value, if exists, if not It will return undefined and continue with the next promise/process with await. So, It will be like this:

return promise.then(() => someAsyncFn())
        .then(() => performSomeOtherAsyncAction() )
        .then(() => doOneLastThing() )

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