2

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?

General Gravicius
  • 181
  • 1
  • 2
  • 10

2 Answers2

3

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);
})();
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
2

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());
Deadron
  • 5,135
  • 1
  • 16
  • 27