如果你定义一个 Promise,async/await 会从上到下执行代码,所以不难。

我做了一些研究,所以这里是一个总结。

样本

让我们创建 Promise a 和 b 并在每个函数中输出一个日志。
它还在每个定义之间以及 Promise.alling a 和 b 之后记录。

const a = new Promise((resolve, reject) => {
  console.log('a');
  resolve('a: resolve');
})
  .then(() => { console.log('a: then'); });

console.log('aの後')

const b = new Promise((resolve, reject) => {
  console.log('b');
  resolve('b: resolve');
})
  .then(() => { console.log('b: then'); });

console.log('bの後')

Promise.all([a, b])
  .then(() => { console.log('c: then'); });

console.log('d');

结果是:

[LOG]: "a" 
[LOG]: "aの後" 
[LOG]: "b" 
[LOG]: "bの後" 
[LOG]: "d" 
[LOG]: "a: then" 
[LOG]: "b: then" 
[LOG]: "c: then"

嗯,then中的输出显示在定义后的d之后。

这怎么发生的

我想习惯写作的人仔细观察就会知道这种行为,但它是一种什么样的规范呢?

当我阅读这些页面时,它的定义如下。

保证
与传统的回调传递不同,Promise 保证以下内容:

  • 在当前 JavaScript 事件循环的当前处理完成之前,绝不会调用 then() 添加的回调。

在示例中所写的情况下,似乎在输出 d 的部分完成后才处理所有内容。
我希望能够根据情况分别编写 async/await 和 then/catch,而不是仅仅以不同的方式编写它们。


原创声明:本文系作者授权爱码网发表,未经许可,不得转载;

原文地址:https://www.likecs.com/show-308626424.html

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-04
  • 2022-12-23
  • 2021-08-23
  • 2021-09-23
猜你喜欢
  • 2021-07-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-19
相关资源
相似解决方案