Siva
Siva

Reputation: 57

Async/Await code not being executes after await

I have been going over async/await. I trying few simple examples but unable to understand flow of async and await . In below code

function wait(ms) {
  return new Promise(r => setTimeout(function() {
    console.log('Hello');
  }, ms));
}

async function GetUser() {
  await wait(5000);
  console.log('world');
}

GetUser();

Why is the message "world" not logged? Only "Hello" prints.

Upvotes: 4

Views: 2555

Answers (3)

Gnanesh
Gnanesh

Reputation: 1

  • Here wait() method returns a Promise, the function of await keyword is to stop code execution until the returned Promise by wait() is resolved.

  • So the code snippet in question, without using async/await will be as below. Note that the resolve function is not yet invoked here. Hence, once the snippet is executed only Hello will get printed in the console.

        // First code snippet
        function wait(ms) {
            return new Promise(r => setTimeout(function () {
                console.log('Hello');
            }, ms));
        }
    
        function GetUser() {
            return wait(1000)
                .then(() => {
                    console.log("World")
                })
                .catch((err) => {
                    console.log(err);
                })
        }
    
        GetUser()

  • Code snippet when r() is invoked. Here, once the snippet is executed Hello and World both are printed in the console.

        // Second code snippet
        function wait(ms) {
            return new Promise(r => setTimeout(function () {
                console.log('Hello');
                r();
            }, ms));
        }
    
        function GetUser() {
            return wait(1000)
                .then(() => {
                    console.log("World")
                })
                .catch((err) => {
                    console.log(err);
                })
        }
    
        GetUser()

  • The reason why the second code snippet works, has to do with how Promise is implemented in JS.

    • Handler function/functions attached to a promise with the help of .then() are invoked only when the promise is resolved.

    • Code snippet when resolve method is not invoked inside the executor function i.e, when the Promise is not resolved. Here, only code inside setTimeout is invoked and not the handlers.

          function wait(ms) {
              return new Promise(r => setTimeout(function () {
                  console.log('Hello');
              }, ms));
          }
      
          const promiseReturnedByWaitMethod = wait(2000);
      
          // Multiple handlers can be added to a promise reference, which are executed when the asynchronous operation is completed.
      
          // adding first handler
          promiseReturnedByWaitMethod.then(() => {
              console.log("First handler!!")
          });
      
          // adding second handler
          promiseReturnedByWaitMethod.then(() => {
              console.log("Second handler!!")
          });

    • Code snippet when resolve method is invoked inside the executor function i.e, when the Promise is resolved.

          function wait(ms) {
                return new Promise(r => setTimeout(function () {
                    console.log('Hello');
                    r();
                }, ms));
            }
      
            const promiseReturnedByWaitMethod = wait(2000);
      
            // Multiple handlers can be added to a promise reference, which are executed when the asynchronous operation is completed.
      
            // adding first handler
            promiseReturnedByWaitMethod.then(() => {
                console.log("First handler!!")
            });
      
            // adding second handler
            promiseReturnedByWaitMethod.then(() => {
                console.log("Second handler!!")
            });

Upvotes: 0

brk
brk

Reputation: 50291

You need to resolve it. So call r()

function wait(ms) {
  return new Promise(r => setTimeout(function() {
    console.log('Hello');
    r()
  }, ms));
}

async function GetUser() {
  await wait(3000)
  console.log('world');
}
GetUser()

Upvotes: 4

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21851

You should call the resolver.

function wait(ms) { 
 return new Promise(r => setTimeout(function(){console.log('Hello'); r();}, 
//                                                                   ^^^ this
ms));
}

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Upvotes: 5

Related Questions