[英]How to use Promise.all correctly?
请考虑以下代码:
var result1;
var result1Promise = getSomeValueAsync().then(x => result1 = x);
var result2;
var result2Promise = getSomeValueAsync().then(x => result2 = x);
await Promise.all([result1Promise, result2Promise]);
// Are result1 and result2 guaranteed to have been set at this point?
console.log(result1 + result2); // Will this always work? Or could result1 and/or result2 be undefined because then() has not been executed yet?
当我使用then()方法时,是否保证按顺序执行? 例如,在Promise.all解决之后,then()不会立即执行吗?
它似乎在Chrome中运行正常,但我真正想要的是保证它总能适用于某些规格吗?
我宁愿不使用Promise.all(...)。然后(一些回调),因为那时我又回到了使用回调...
只有在其数组中的所有promise都已解决后, Promise.all
才会解析。 因为你的两个承诺有以下.then
:
.then(x => result1 = x);
.then(x => result2 = x);
一旦这两个功能完成, Promise.all
将解决。 所以是的,当Promise.all
回调运行时, result1
和result2
都保证被定义(或者至少被分配给)。
仍然,不是分配外部变量,而是在 await
Promise.all
用const
定义变量更有意义:
const [result1, result2] = await Promise.all([getSomeValueAsync(), getSomeValueAsync()]);
您可以直接使用Promise.all
的返回值:
const p1 = getSomeValueAsync();
const p2 = getSomeValueAsync();
const [result1, result2] = await Promise.all([p1, p2]);
console.log(result1 + result2);
是的,他们已经确定。 解析result1Promise和result2Promise包括设置result1和result2,因为只有在执行.then()时才能完全解析promise本身。
但是,如果你想避免回调,你应该像这样构建你的代码:
const result1Promise = getSomeValueAsync();
const result2Promise = getSomeValueAsync();
const results = await Promise.all([result1Promise, result2Promise]);
console.log(results[0] + results[1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.