【问题标题】:Promise.all inside an asynchronous function [duplicate]异步函数中的 Promise.all [重复]
【发布时间】:2019-12-21 06:43:49
【问题描述】:

我有 2 个代码

1 个代码

async function foo() {
    const result1 = asyncFunc1();
    const result2 = asyncFunc2();
    return [result1, result2];
}

2 代码

async function foo() {
    const [result1, result2] = await Promise.all([
        asyncFunc1(),
        asyncFunc2(),
    ]);
return [result1,result2];
}

问题 两者有区别吗?

【问题讨论】:

  • 如果第一个示例中有awaits,它将是串行的,而不是并行的。
  • 你在第一个例子中没有使用await,所以你不需要等待异步函数的完成,因此result1result2将等于promise而不是result价值观
  • @OlivierBoissé 表示 1 个代码同步 2 个代码异步?

标签: javascript ecmascript-6


【解决方案1】:

根据 cmets,两者基本上没有区别,除了您没有等待两个异步函数的结果,因此您最终只会得到 promise 对象。异步函数不会自动等待范围内的 Promise / 异步代码,它们只是允许您使用 await 关键字,它只是停止执行,直到底层的 Promise 得到解决。

这里试图说明这些差异。

需要注意的是,第一个函数的返回值不是预期的 1、2。

const asyncFunc = (a) => {
    return new Promise((resolve) => {   
      setTimeout(() => resolve(a), 1000);
  })
}

const asyncFunc1 = () => asyncFunc(1);
const asyncFunc2 = () => asyncFunc(2);

async function foo() {
    const result1 = asyncFunc1();
    const result2 = asyncFunc2();
    return JSON.stringify({ result1, result2 });
}

async function foo2() {
    return [result1, result2] = await Promise.all([
        asyncFunc1(),
        asyncFunc2(),
    ]);
}


(async () =>{
    const el = document.createElement('div');
    el.appendChild(document.createTextNode(await foo()));
    el.appendChild(document.createTextNode(await foo2()));
    document.querySelector('body').appendChild(el);
})();


// {"result1":{},"result2":{}} 1,2

这是一个可以玩弄的小提琴; jsfiddle.

【讨论】:

  • compilation 在这里绝对是错误的词,你的意思是 execution 吗?
  • 是的,绝对是指执行。谢谢。
【解决方案2】:

只要找出来!这是一个显示所有主要差异的 sn-p:

const timer = ms => new Promise(res => setTimeout(res, ms));

async function one() {
  console.log("1 one called");
  await timer(2000);
  console.log("1 one done");
}

async function two() {
  console.log("2 two called");
  await timer(1000);
  console.log("2 two done");
  // throw new Error; // Uncomment to see another interesting behaviour
}

(async function main() {
  const startParallel = Date.now();
  await Promise.all([one(), two()]);
  console.log(`parallel done, took ${Date.now() - startParallel}`);

  const startSerial = Date.now();
  await one();
  await two();
  console.log(`serial done, took ${Date.now() - startSerial}`);
})();

【讨论】:

    【解决方案3】:

    正如 cmets 所说,您没有等待第一个 sn-p 中的函数调用,因此您将得到 promise 作为返回值。但是,如果您使用 await,一个主要区别是在第一个 sn-p 中,asyncFunc2 不会执行,直到 asyncFunc1 得到解决(假设您使用 await)。而在第二个 sn-p 中,asyncFunc2asyncFunc1 之后立即执行,无论它是否已解决。

    Promise.all 将按照您传递函数的顺序返回结果。

    请参阅 Promise.AllAwait 的文档

    【讨论】:

    • 要明确的是,第一个sn-p当前没有使用await,所以除了第一个sn-p不等待结果之外,sn-ps是一样的。
    • @FINDarkside 不错,已更新。
    猜你喜欢
    • 2019-10-19
    • 2021-11-07
    • 2020-08-03
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    相关资源
    最近更新 更多