Return values from async functions

How do you return anything from async functions? How do you receive what is returned from async functions?

Previously we have seen how return works in Javascript. I typically write functions that return at least a true or false value.

function printThis(statement) {
  console.log(statement);
  return true;
}

const ret = printThis("hello world");
console.log(ret);

/* output
hello world
true
*/

If the function described above is async -

async function printThis(statement) {
  console.log(statement);
  return true;
}

const ret = printThis("hello world");
console.log(ret);

/* output
hello world
Promise { true }
*/

If you are interested in the return value from an async function, just wait till the promise resolves. Use then or wrap function in await.

async function printThis(statement) {
  console.log(statement);
  return true;
}

const ret = printThis("hello world").then(ret => console.log(ret));

/* output
hello world
true
*/

Also see

comments powered by Disqus