admin管理员组

文章数量:1336367

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();

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.

Share Improve this question edited Dec 10, 2018 at 15:51 Siva asked Dec 7, 2018 at 15:12 SivaSiva 572 silver badges10 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

You should call the resolver.

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

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

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()

  • 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 pleted.
      
          // 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 pleted.
      
            // adding first handler
            promiseReturnedByWaitMethod.then(() => {
                console.log("First handler!!")
            });
      
            // adding second handler
            promiseReturnedByWaitMethod.then(() => {
                console.log("Second handler!!")
            });

本文标签: javascriptAsyncAwait code not being executes after awaitStack Overflow