javascript - 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。
所以这就是问题,它真的一样吗,或者第二种方法是否有任何性能改进?非常欢迎提供证明!
解决方案
我的团队负责人说,这两种方法最终都采用了相同的解决方案(两个功能并行执行)。
这是不正确的。
但是,据我所知,第一种方法会
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
推荐阅读
- swift - 使用 SpriteKit 呈现 UIViewController 时口吃
- ios - 用自定义颜色填充边框矩形
- laravel - 使用 Guzzle 7 发送 JSON POST 和标头的正确方法是什么?
- react-native - Expo React Native BarCodeScanner 在我第二次打开时崩溃
- reactjs - 再次调用同一路线时,mapStateToProps 未调用
- elasticsearch - Mule elestic 搜索配置
- typescript - 如何动态地从 TypeScript 文件中导入常量?
- python - 如何在循环中创建页面,tkinter?
- android - 我正在尝试从我的 firebase 中检索数据,但不知何故,时间戳是以 java.util.data 格式接收的
- javascript - 从 html 代码中删除函数和属性