首页 > 解决方案 > Promise.all vs [await x, await y] - 真的一样吗?

问题描述

这是一个基本问题,但我无法在任何地方找到答案。

我们有两种方法:

// consider someFunction1() and someFunction2() as functions that returns Promises

Approach #1:
return [await someFunction1(), await someFunction2()]

Approach #2:
return await Promise.all([someFunction1(), someFunction2()])

我的团队负责人说,这两种方法最终都采用了相同的解决方案(两个功能并行执行)。但是,据我所知,第一种方法会await someFunction1()先解决,然后再执行 someFunction2。

所以这就是问题,它真的一样吗,或者第二种方法是否有任何性能改进?非常欢迎提供证明!

标签: javascriptnode.jses6-promise

解决方案


我的团队负责人说,这两种方法最终都采用了相同的解决方案(两个功能并行执行)。

这是不正确的。

但是,据我所知,第一种方法会await someFunction1()先解决,然后再执行 someFunction2。

那是对的。

这是一个演示

方法一:

const delay = (ms, value) =>
  new Promise(resolve => setTimeout(resolve, ms, value));
  
async function Approach1() {
  return [await someFunction1(), await someFunction2()];
}
  
async function someFunction1() {
  const result = await delay(800, "hello");
  console.log(result);
  return result;
}

async function someFunction2() {
  const result = await delay(400, "world");
  console.log(result);
  return result;
}

async function main() {
  const start = new Date();
  const result = await Approach1();
  const totalTime = new Date() - start;
  console.log(`result: ${result}
    total time: ${totalTime}`);
}

main();

结果是:

hello
world
result: hello,world
    total time: 1205

这意味着首先someFunction1运行完成然后执行。它是顺序的someFunction2

方法二:

const delay = (ms, value) =>
  new Promise(resolve => setTimeout(resolve, ms, value));
  
async function Approach2() {
  return await Promise.all([someFunction1(), someFunction2()]);
}
  
async function someFunction1() {
  const result = await delay(800, "hello");
  console.log(result);
  return result;
}

async function someFunction2() {
  const result = await delay(400, "world");
  console.log(result);
  return result;
}

async function main() {
  const start = new Date();
  const result = await Approach2();
  const totalTime = new Date() - start;
  console.log(`result: ${result}
    total time: ${totalTime}`);
}

main();

结果是:

world
hello
result: hello,world
    total time: 803

这意味着在 之前someFunction2完成。两者是平行的。 someFunction2


推荐阅读