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

时间:2018-08-17 17:58:17

标签: javascript async-await

看看下面的代码:

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 个答案:

答案 0 :(得分:2)

您需要将代码编写为:

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

结果:

  

//第10行:超时

     

//第16行:超时

     

//全部完成