0

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?

  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – philoez98 Jun 18 '19 at 22:03

2 Answers2

0

An async function is guaranteed to return Promise, but when that Promise settles and what it delivers are determined by what the function returns.

Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
  • And for example if `bar` returns a Promise, is it the same to return or not return it? –  Jun 18 '19 at 22:00
  • No, similar as a normal function, if nothing is explicitly returned, then an async function will return Promise. – Roamer-1888 Jun 18 '19 at 22:03
0

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'

pseudosavant
  • 7,056
  • 2
  • 36
  • 41