Async function doesn't wait with await before returning

Viewed 860

Consider the following code:

const getName = () => 
  new Promise(resolve => setTimeout(resolve, 1000, 'xxx'));

f = async () => {
  let name = await getName();
  console.log(name);
  return name;
}

console.log(f());

The function will wait before printing "name" but it will still return the promise instead of the result and won't print the correct output outside the function. Is there a way around this?

2 Answers

You need to await for f(). Here is an example:

const getName = () => 
  new Promise(resolve => setTimeout(resolve, 1000, 'xxx'));

const f = async () => {
  const name = await getName();
  console.log("1. "+name);
  return name;
}

const run = (async () => {
  const ret = await f();
  console.log("2. "+ret);
})();

You need to await the promise returned by the f function. That is why its printing a promise instead of a result.

console.log(await f());
Related