Search code examples
javascriptasync-awaites6-promise

Console log not printing in awaited promise in an async function


  function sleep(cb, ms) {
    return new Promise((cb) => setTimeout(cb, ms));
  }

  async function delayedGreeting() {
    console.log("Hello");
    await sleep(myfun, 1000);
    console.log("World!");
  }

  function myfun() {
    console.log("whatever");
  }

  delayedGreeting();
  console.log("Goodbye!");

Can someone please explain in the context of Eventloop, Callback Queue and Stack as to what is happening here as I don't see the word 'whatever' in the output. Is there a mistake in the code and if so what is it?


Solution

  • There are some minor mistakes in the code. I am pointing them below.

    1. You should write resolve in the Promise.
    return new Promise((resolve) => resolve (setTimeout(()=>{cb()}, ms)));
    
    1. If you want myfun to run after a timeout of 1000 millisecond, you must call the function in the settimeout first parameter. Like this,
    setTimeout(()=>{cb()}, ms);
    

    Here is the updated source code,

          function sleep(cb, ms) {
            return new Promise((resolve) => resolve (setTimeout(()=>{cb()}, ms)));
          }
    
          async function delayedGreeting() {
            console.log("Hello");
            await sleep(myfun, 1000);
            console.log("World!");
          }
    
          function myfun() {
            console.log("whatever");
          }
    
          delayedGreeting();
          console.log("Goodbye!");

    And the right output according to the implementation that you are trying the code should be like this,

    Hello
    Goodbye!
    World!
    whatever