Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

await doesn't wait for the function to end

I'm new to javascript and I tried to implement my first async await and can't figure out where is my problem.

getName() - should return a promise after 1s. f() - should wait for getName to finish and then print name

What am I missing ?

const getName = async () => {
  setTimeout(() => 'xxx', 1000)
};

const f = async () => {
  name = await getName()
  console.log(name)
}

f()
like image 285
Htpc Rad Avatar asked Feb 07 '19 21:02

Htpc Rad


People also ask

Does await wait for function to finish?

The keyword Await makes JavaScript wait until the promise returns a result. It has to be noted that it only makes the async function block wait and not the whole program execution. The code block below shows the use of Async Await together.

Does await wait for then?

The await keyword before a promise makes JavaScript wait until that promise settles, and then: If it's an error, an exception is generated — same as if throw error were called at that very place.

Does await stop for loop?

You need to place the loop in an async function, then you can use await and the loop stops the iteration until the promise we're awaiting resolves.


2 Answers

Unless you're using await also inside getName, you don't need to have getName async, you just need to return a Promise; since await works with promises:

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

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

f();
like image 128
ZER0 Avatar answered Oct 13 '22 18:10

ZER0


To await a function, that function must return a promise.

You thus need to create a new promise. It will have 2 methods: resolve, and reject.

  1. resolve returns the variable, and is used on success. You can catch its return value by using promise.then(value => ) or by awaiting it.
  2. reject throws an error, and is used on error. You can catch the error by using promise.catch(err => ) or by awaiting the async function and wrapping it in a try-catch block.

Here is how your code should look:

const getName = async () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('xxx');
    }, 1000)
  })
};

const f = async () => {
  name = await getName()
  console.log(name)
}

f()
like image 34
MadWard Avatar answered Oct 13 '22 17:10

MadWard