javascript - 如何正确使用Promise.all?

标签 javascript asynchronous

考虑以下代码:

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/

相关文章:

ios - 对象-C : dispatch_async crashes without NSLog

javascript - 如何在 React/Redux 中打印标准化数据

javascript - Javascript 如何从没有对象名称的对象中获取值

javascript - AWS Lambda 上的 promise 得到解决后,.then 不会运行

java - 异步检索 SQL 查询执行结果。

javascript - 这怎么能等到更新完才移到下一项呢?

asynchronous - 一旦异步: run f# async function exactly once

javascript - 模块化 Vue 需要哪些 NPM 依赖项?

javascript - 使用服务器路由 react 路由器浏览器历史记录

javascript - 如何使用应用程序脚本在 html 模板中制作表格