考虑以下代码:
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(某些回调),因为那样我会再次使用回调...
最佳答案
您可以直接使用 Promise.all
的返回值:
const p1 = getSomeValueAsync();
const p2 = getSomeValueAsync();
const [result1, result2] = await Promise.all([p1, p2]);
console.log(result1 + result2);
关于javascript - 如何正确使用Promise.all?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56542219/