I want to use JavaScript async/await

Given the following code:

function timer1(){
  return new Promise(()=>{
    setTimeout(() => {
      console.log("1...");
    }, 1000);
  })
}
function timer2(){
  return new Promise(()=>{
    setTimeout(() => {
      console.log("2...");
    }, 2000);
  })
}
function timer3(){
  return new Promise(()=>{
    setTimeout(() => {
      console.log("3...");
    }, 3000);
  })
}
async function timers(){
  await timer3();
  await timer2();
  await timer1();
}
timers();

The output is:

(After 3 seconds..)
3...

I want to get this result:

(After 3 seconds..)
3...
(After 2 seconds..)
2...
(After 1 seconds..)
1...

Why is only one(3…) printed?
I want to print out all three.

>Solution :

You need to resolve the Promise when it’s finished. Otherwise, it’s never considered to be done, remaining forever in a pending state, and timer2 will never be executed.

The function passed to the Promise constructor gets passed two parameters, which are functions to call to either terminate successfully or with a failure.

function timer1(){
  return new Promise((resolve, reject) =>{
    setTimeout(() => {
      console.log("1...");
      resolve();
    }, 1000);
  })
}
function timer2(){
  return new Promise((resolve, reject) =>{
    setTimeout(() => {
      console.log("2...");
      resolve();
    }, 2000);
  })
}
function timer3(){
  return new Promise((resolve, reject) =>{
    setTimeout(() => {
      console.log("3...");
      resolve();
    }, 3000);
  })
}
async function timers(){
  await timer3();
  await timer2();
  await timer1();
}
timers();

Leave a Reply