AmerllicA
AmerllicA

Reputation: 32472

Async/Await doesn't work in my example

Many JavaScript developers know about async/await and benefits of them so I try to test a old example of asynchronous action, let's see my experiment:

Undoubtedly the answer of below code is:

/*Line: 1*/ console.log(`1`);
/*Line: 2*/ console.log(`2`);
/*Line: 3*/ console.log(`3`);

//==>  123

So I wanna put a setTimeout for second line:

/*Line: 1*/ console.log(`1`);
/*Line: 2*/ setTimeout(() => {
               console.log(`2`);
            }, 0);
/*Line: 3*/ console.log(`3`);

//==> 132

Because of asynchronous action of second line the 2 is after the 13, so in the console 132 is showed.

I decide to use async/await feature of new JavaScript to see 123 again, so I wrote the above code like this:

(async () => {
    console.log(`1`);
    await setTimeout(() => {
        console.log(`2`);
    }, 0);
    console.log(`3`);
})();

But it doesn't work and I saw 132 again in my console. Which part I did wrong or I don't know about it?

Upvotes: -1

Views: 613

Answers (5)

Javier Cobos
Javier Cobos

Reputation: 1182

setTimeout is not returning a promise. In order to get it to work, you will have to create a function returning a promise that is resolved inside the setTimeout callback.

(async () => {
    console.log(`1`);
    await new Promise(resolve => {
	    setTimeout(() => {
		    resolve('resolved');
		    console.log(`2`);
	    },0);
    });
    console.log(`3`);
})();

Upvotes: 1

Nir Levy
Nir Levy

Reputation: 4740

Await should be called on a function that returns a promise (otherwise it just returns).

setTimeout does not return a promise so you should wrap it with a function that returns a promise.

Read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

This code should do the work.

(async() => {
  console.log(`1`);
  await (() => {
    return new Promise( resolve => {
      setTimeout(() => {
        console.log(2);
        resolve()
      }, 1000);
    });
  })();
  console.log(`3`);
})();

Upvotes: 1

Faly
Faly

Reputation: 13346

You can only await a function which returns a promise. Note that await can only be used inside an async function:

async function someFunc() {
  console.log(`1`);
  await new Promise((resolve, reject) => setTimeout(() => {
      console.log(`2`);
      resolve();
  }, 0));
  console.log(`3`);
}

someFunc();

Upvotes: 1

Raeesaa
Raeesaa

Reputation: 3316

await waits for promise to be resolved. Since setTimeout is not a promise, execution of program will not wait till it is executed. You would need to wrap setTimeout() within promise as specified in first example of following link for your example to work as expected:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Upvotes: 2

MikeSpiris
MikeSpiris

Reputation: 73

You need to create function, for example async function foo() {}, and make await calls inside it.

Upvotes: 0

Related Questions