考虑以下代码:
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) 因为然后我又会再次使用回调...
最佳答案
可以直接使用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/