Search code examples
javascriptasync-awaitpromisesettimeoutes6-promise

How does one await the result of a deferred operation with setTimeout?


function z(){
setTimeout(()=>{
        console.log("A")
    },3000)
}

z()
console.log("B")

output i expected

A(3 sec delay)

B

output i got

B

A(3 sec delay)

how to get synchronous behavior with this asynchronous code?


Solution

  • For a first solution the OP needs to ...

    • write a wait function which accepts a number value (representing milliseconds) and returns a Promise instance which resolves after the provided delay.
    • utilize the wait function by logging the to be delayed value after the awaited time via the promise' then method.

    function wait(msec) {
      return new Promise(resolve =>
        setTimeout(resolve, msec)
      );  
    }
    
    console.log('A');
    wait(3000)
      .then(() => console.log('B'));
    .as-console-wrapper { min-height: 100%!important; top: 0; }

    For a second solution the above provided code could be rewritten into an async function which does log both of the OP's values and does, in between the logging, await the promise returned by wait.

    function wait(msec) {
      return new Promise(resolve =>
        setTimeout(resolve, msec)
      );  
    }
    
    (async () => {
    
      console.log('A');
      await wait(3000);
      console.log('B');
    
    })();
    .as-console-wrapper { min-height: 100%!important; top: 0; }