考虑以下代码:
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(...)。then(某些回调),因为那样我会再次使用回调...
答案 0 :(得分:5)
Promise.all
仅在其数组中的所有promise都解决后才能解决。因为您的两个承诺中有.then
个:
.then(x => result1 = x);
.then(x => result2 = x);
这两个功能完成后,Promise.all
将解决。因此可以,保证result1
和result2
都在运行Promise.all
回调时被定义(或至少已分配给)。
不过,与其分配外部变量,不如使用const
而 await
定义Promise.all
来定义变量:>
const [result1, result2] = await Promise.all([getSomeValueAsync(), getSomeValueAsync()]);
答案 1 :(得分:4)
您可以直接使用Promise.all
的返回值:
const p1 = getSomeValueAsync();
const p2 = getSomeValueAsync();
const [result1, result2] = await Promise.all([p1, p2]);
console.log(result1 + result2);
答案 2 :(得分:2)
是的,它们已设置。解决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]);