首页 > 解决方案 > 并行使用 async / await 并在结果到达时获得结果?

问题描述

我需要执行多个 ajax 获取来填充网页,并希望在结果到达时呈现页面的不同部分。是否可以使用 async / await 语法来做到这一点,还是我必须使用 Promise 进行旧式回调?

这个问题类似,但没有答案:Call async/await functions in parallel这个问题中接受的答案是使用 Promise.all(...),在所有结果解决之前不会返回任何结果.

我知道我可以这样做:

myPromise.then(function(value) {
  // populate part of page here
});

myOtherPromise.then(function(value) {
  // populate other part of page here
});

但我正在尝试使用较新的 await 语法。

标签: javascriptasync-await

解决方案


你可以使用类似的东西:

(async () => {
    const value = await myPromise;
    // then do your stuff with value
})();

(async () => {
    const value = await myOtherPromise;
    // then do your stuff with value
})();


推荐阅读