代码之家  ›  专栏  ›  技术社区  ›  Mehran

为什么在JS中调用异步函数不阻塞?

  •  0
  • Mehran  · 技术社区  · 6 年前

    请看下面的代码:

    function promised() {
        return new Promise((resolve) => {
            setTimeout(() => resolve('Timeout'), 1000);
        });
    }
    
    async function awaited()
    {
      const r = await promised();
      console.log('Line 10: ' + r);
      return r;
    }
    
    function start() {
      const r = awaited();
      console.log('Line 16: ' + r);
    }
    
    start();
    
    console.log("All done");
    

    运行此代码时,您将得到:

    Line 16: [object Promise]
    All done
    Line 10: Timeout
    

    但我希望得到:

    Line 10: Timeout
    Line 16: Timeout
    All done
    

    我的期望是 await 应该在第9行阻止执行。但似乎不是!我的问题是为什么?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Any Moose    6 年前

        function promised() {
          return new Promise(resolve => {
            setTimeout(() => resolve("Timeout"), 1000);
          });
        }
        
        async function awaited() {
          const r = await promised();
          console.log("Line 10: " + r);
          return r;
        }
        
        function start() {
          const r = awaited();
          // r here is a promise, so you need to call then to wait until
          // awaited is finished.
          return r.then(d => console.log("Line 16: " + d));
        }
        
        start().then(() => console.log("All done"));