【问题标题】:Async/await is blocking? if not why its result is different from promises?异步/等待阻塞?如果不是,为什么它的结果与承诺不同?
【发布时间】:2021-11-25 22:00:25
【问题描述】:

我对 async/await 做了一些研究,但我很困惑。它说 async/await 是非阻塞的。我研究了 developer.mozilla.org 异步函数示例。 参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');

  const result = await resolveAfter2Seconds();
  console.log(result);

  //uncomment this code to see promise result
  //resolveAfter2Seconds().then(result=>{
  //console.log(result);
  //});

  console.log('calling end');
}

asyncCall();

async/await 结果是

> "calling"
> "resolved"
> "calling end"

但承诺结果是

> "calling"
> "calling end"
> "resolved"

所以如果 async/await 是非阻塞的,那么为什么它不会在“解决”之前控制台“调用结束”??

【问题讨论】:

  • await 没有阻塞。它允许编写异步代码,如同步代码,并按照编写顺序执行行,同时是非阻塞的(超时、间隔、HTTP 请求等仍然同时运行)。 .then() 根本不这样做。 .then() 中的内容不会在写入时执行,而是稍后执行。您的示例有缺陷,两个代码不等效,这就是您得到两个不同结果的原因。
  • @zhulien 能否提供一些博客或文档参考资料,我将在其中进行更详细的研究?

标签: javascript async-await


【解决方案1】:

您的 Promise 代码与异步变体不同。

async function asyncCall() {
  console.log('calling');
  
  const result = await resolveAfter2Seconds();
  console.log(result);
  
  console.log('calling end');
}

相同
function asyncCall() {
  console.log('calling');

  resolveAfter2Seconds()
    .then(result => {
      console.log(result);

      console.log('calling end');
    });
}

【讨论】:

  • 不会有 2 个.then,只有一个,因为没有更多的awaits 参与。
  • 没错,我只是扩展了他的示例,该示例已经有第一个 then(),但我会修复它。
【解决方案2】:

正如@zhulien 提到的,await 关键字是魔法。

为了更好地理解它,执行以下代码:

await

asyncCall();
console.log("this log you will see right after 'calling' log");

没有await(只需在 asyncCall 中删除 await - 嘿,你知道在没有 await 的情况下使用 async 很好,但反之则不行)。

asyncCall();
console.log("this log you will see right after 'calling end' log");

所以在同一个闭包中,await 之后的任何内容都将被阻塞,而代码流从调用函数继续,这就是文档中非阻塞的含义:)

【讨论】:

    猜你喜欢
    • 2019-10-20
    • 1970-01-01
    • 2019-04-29
    • 2018-02-03
    • 2018-03-05
    • 1970-01-01
    • 2019-06-30
    • 2019-10-16
    • 2017-02-03
    相关资源
    最近更新 更多