Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading