gpt4 book ai didi

javascript - 并行使用 async/await,并在结果到达时获取结果?

转载 作者:行者123 更新时间:2023-12-02 22:45:28 25 4
gpt4 key购买 nike

我需要执行多次 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
});

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

最佳答案

你可以使用类似的东西:

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

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

关于javascript - 并行使用 async/await,并在结果到达时获取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58422403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com