简体   繁体   中英

Does an 'async' function immediately return resolve(undefined) unless this is explicitly overrided?

By overriding an async function's immediate return of resolve(undefined), I mean using:

return new Promise(resolve, reject)... resolve(variableName)

Also, if this is indeed the default behaviour, are there any other ways to override this?

Edit: New understanding thanks to @Quentin. Please correct the following if wrong.

When you call an async function like async function1() {... without await:

function1 will block (only 'asyncing' tasks with await or then) and will run to completion.

function1 does not immediately return anything (ie an empty, undefined, or pending promise).

function1 returns Promise {undefined} if there's no explicit return statement.

function1 returns Promise { pending } if there's await or return new Promise.. , as these add a task to the event loop microtask queue.

And function1 fulfils/rejects the promise with a value if return varName is used.

An async function will run and return a promise.

When the function gets to the end, it will resolve that promise with what would normally be the return value. (If you use await inside, then the promise won't be resolved until the async function unfreezes and reaches the end.)

The default return value for a function without a return statement is undefined , so if you don't include a return statement it will return a promise that resolves with undefined .

If you return a promise, then it will return a promise resolved with that promise which will be adopted as normal.

If you return something else, then the promise will be resolved with that value.

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