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

403 views Asked by At

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();
        });
}
2

There are 2 answers

0
Felix Kling On BEST ANSWER

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.

0
damianfabian On

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