【问题标题】:First promise inside Promise.all() doesn't execute properlyPromise.all() 中的第一个承诺没有正确执行
【发布时间】:2021-09-08 04:26:16
【问题描述】:

wait 函数用作睡眠函数,fn 函数接受一个数组(项目),它记录每个项目并在记录下一个项目之前休眠一秒钟。

const wait = async(time) => {
  return new Promise((resolve) => setTimeout(resolve, time))
}

const fn = async(items) => {
  for (item of items) {
    await wait(1000)
    console.log(item)
  }
}

const exeAll = async() => {
  Promise.all([
    fn(['A1', 'A2']),
    fn(['B1', 'B2']),
  ])
}

exeAll()

问题是exeAll 函数提供的打印结果:

B1
A2
B2
B2

但我认为它应该打印如下内容:

A1
B1
A2
B2

执行上述代码时,A1 根本不显示。谁能解释一下为什么?

【问题讨论】:

  • 如果您在Promise.all() 调用中await 调用fn(),它会完全按照您的预期工作。
  • 并且 B2 最后总是记录两次。
  • exeAll 不需要异步。
  • 我不想await他们,等待他们让他们按顺序执行。这将打印:A1 A2 B1 B2
  • 我已经从 exeAll 函数中删除了 async 关键字,但没有任何改变,问题始终存在。 A1 不打印,B2 打印两次。

标签: javascript asynchronous async-await promise


【解决方案1】:

for (item of items) { 将创建一个隐式全局变量item,即多次调用fn 将相互干扰,覆盖item。正确声明变量并按预期工作:

const wait = async(time) => {
  return new Promise((resolve) => setTimeout(resolve, time))
}

const fn = async(items) => {
  for (let item of items) {
  //   ^^^^
    await wait(1000)
    console.log(item)
  }
}

const exeAll = async() => {
  Promise.all([
    fn(['A1', 'A2']),
    fn(['B1', 'B2']),
  ])
}

exeAll()

我们可以向fn 添加更多日志记录,看看在您的情况下会发生什么:

const wait = async(time) => {
  return new Promise((resolve) => setTimeout(resolve, time))
}

let counter = 0;
const fn = async(items) => {
  const c = counter++;
  console.log(`enter fn call #${c}`);
  for (item of items) {
    console.log(`fn call #${c} sets item <-`, item);
    await wait(1000)
     console.log(`fn call #${c} reads item ->`, item);
    console.log(item)
  }
}

const exeAll = async() => {
  Promise.all([
    fn(['A1', 'A2']),
    fn(['B1', 'B2']),
  ])
}

exeAll()

严格模式 ("use strict";) 会发现该错误,因为分配给未声明的变量会引发错误。

【讨论】:

  • 严格模式 ("use strict";) 会发现这一点,因为分配给未声明的变量会引发错误;)
  • 没错。当我第一次看到你的回答时,我首先想到的是“严格模式”。
猜你喜欢
  • 1970-01-01
  • 2022-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多