3

To understand async/await, I am trying to display a console message once settimeout runs and expires. How do I fix my code below? I have 5 settimeout function and each should display respective message once finished.

function t1(){
    setTimeout(() => {
    console.log("1")
    }, 1000);
}

function t2(){
    setTimeout(() => {
    console.log("2")
    }, 2000);
}

function t3(){
    setTimeout(() => {
    console.log("3")
    }, 3000);
}

function t4(){
    setTimeout(() => {
    console.log("4")
    }, 4000);
}

function t5(){
    setTimeout(() => {
    console.log("5")
    }, 5000);
}

async function main(){
    await t1();
    console.log("1sec done");
    await t2();
    console.log("2sec done");
    await t3();
    console.log("3sec done");
    await t4();
    console.log("4sec done");
    await t5();
    console.log("Yay! I am all done");
}
main();

1
  • async-await is for promises. Commented Mar 20, 2019 at 8:12

3 Answers 3

4

You should use Promises

function t1(){
    return new Promise(function(resolve, reject) {
      setTimeout(() => {
        console.log("1");
        resolve();
      }, 1000);
   });
}

function t2(){
    return new Promise(function(resolve, reject) {
      setTimeout(() => {
        console.log("2");
        resolve();
      }, 1000);
   });
}

function t3(){
    return new Promise(function(resolve, reject) {
      setTimeout(() => {
        console.log("3");
        resolve();
      }, 1000);
   });
}

function t4(){
    return new Promise(function(resolve, reject) {
      setTimeout(() => {
        console.log("4");
        resolve();
      }, 1000);
   });
}

function t5(){
    return new Promise(function(resolve, reject) {
      setTimeout(() => {
        console.log("5");
        resolve();
      }, 1000);
   });
}

async function main(){
    await t1();
    console.log("1sec done");
    await t2();
    console.log("2sec done");
    await t3();
    console.log("3sec done");
    await t4();
    console.log("4sec done");
    await t5();
    console.log("Yay! I am all done");
}
main();

Sign up to request clarification or add additional context in comments.

Comments

2

You are doing two mistakes

  • First you are using await before a calling a function t1,t2,t3.... await should be used on Promises.
  • You are passing 1000,2000,... to setTimeout(). You should create a function which returns a Promise which will be resolved after 1 second
  • Use await before the promise returned by that function

let afterOne = (num) => new Promise(res => {
    setTimeout(()=>{
      //log the number passed to function after 1000 ms
      console.log(num);
      //resolve the current promise so then next setTimeout could be set
      res();
   },1000)
  })
async function main(){
    /*This loop does same as
       await afterOne(0);
       await afterOne(1);
       await afterOne(2)
       await afterOne(3);
       await afterOne(4);
    */
    for(let i = 0;i<5;i++){
      await afterOne(i)
    }
}
main();

Comments

1

For each of the functions t1() through t5(), you'll need to ensure these return a Promise such that the returned promise is "resolved" once the respective setTimeout() timer inside has completed.

By returning the Promise object in this way, your t1() -> t5() functions effectivly become async methods, which in turn means than the await prefix will cause execution of main() to block until each t1() -> t5() function has completed (or "been resolved").

To illustrate this, consider the following code where a generic delay() function replaces the t1() -> t5() functions in your original code:

/* I've defined a generic delay function as replacement
for t1 - t5 functions to minimise the amount of code */
function delay(seconds) {

  /* Return a promise object that will cause the
  await to prevent main() async function's execution
  from continuing until this promise has resolved */
  return (new Promise((resolve) => {

    /* Inside the promise, set your time out */
    setTimeout(() => {
      console.log(seconds)

      /* When time out complete, call resolve(), which
      resolves this promise and allows main() async 
      function's execution to continue */
      resolve()
    }, seconds * 1000);

  }))

}

async function main() {
  await delay(1);
  console.log("1sec done");
  await delay(2);
  console.log("2sec done");
  await delay(3);
  console.log("3sec done");
  await delay(4);
  console.log("4sec done");
  await delay(5);
  console.log("Yay! I am all done");
}
main();

2 Comments

I have read that putting async before a function will make it return promise. So If I declare those t1-t5 functions like as async function t1(){...}, will it make any difference, as it will be returning promises also?
Putting async before your function declaration won't cause that function to automatically behave the way you're wanting it to here. Doing that basically means you are able to use theawait keyword when calling other asynchronous functions from inside of the t1() function for instance - hope that helps 😊

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.