【发布时间】:2019-06-11 19:16:19
【问题描述】:
考虑以下代码:
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(some callback) 因为那样我又要重新使用回调了...
【问题讨论】:
-
是的,可以,
.then只是await的替代品 -
@CertainPerformance Yes :) 但我认为您错过了问题的重点,即 then() 回调的执行顺序。例如,如果第 1 行的 then() 回调在 Promise.all 的 then 之后执行,它将不起作用。
-
您是否更愿意为外部变量赋值而不是使用
Promise.all调用的返回值? -
@SamuelVaillant 啊!这就是我应该做的。我不知道 Promise.all 返回了这些值。