简体   繁体   中英

Return from async function

I wonder if it is mandatory to return from an async function, for example:

async function foo() {
  return bar(); // bar returns a promise
}

or can I just do

async function foo() {
  bar();
}

because async will automatically return a promise but should I return the original promise and not a new one auto-created by async?

确保异步函数返回Promise,但是当Promise结算并且它传递的内容由函数返回的内容决定。

It depends on if you want a value to be passed to the next promise in the chain. It is normally a good practice to return a value to the promise unless it is the last function in the chain, or there isn't information to pass on (for some reason).

If the only reason bar() is being called is because it causes some side-effect outside the function (changes a global var, updates a DB, etc) I suppose you could not return. But even then I still would return some value for success, especially if bar() performed I/O.

function bar(){
  return 'hello world';
}

async function foo1() {
  bar(); // Returns a promise with an empty value
}

async function foo2() {
  return bar(); // returns a promise with the _value_ returned from bar()
}

foo1().then(console.log); // undefined
foo2().then(console.log); // 'Hello World'

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