【问题标题】:Async/Await code not being executes after await等待后未执行异步/等待代码
【发布时间】:2018-12-07 15:12:55
【问题描述】:

我一直在讨论异步/等待。我尝试了一些简单的示例,但无法理解 async 和 await 的流程。在下面的代码中

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

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

GetUser();

为什么没有记录“世界”消息?只打印“Hello”。

【问题讨论】:

    标签: javascript asynchronous async-await


    【解决方案1】:

    你需要解决它。所以打电话给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()

    【讨论】:

      【解决方案2】:

      你应该调用解析器。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-07
        相关资源
        最近更新 更多