javascript - 并行使用 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 语法。
解决方案
你可以使用类似的东西:
(async () => {
const value = await myPromise;
// then do your stuff with value
})();
(async () => {
const value = await myOtherPromise;
// then do your stuff with value
})();
推荐阅读
- linux - 如何去除传输到 sink Vim FZF 的匹配内容前面的空格?
- excel - 运行时错误“3706”。找不到提供者。可能没有正确安装”
- android - 任务 :app:uploadCrashlyticsMappingFileRelease FAILED 预期的文件集合只包含一个文件,但是,它不包含任何文件
- python - 如何在 PYOMO 中分配虚拟二进制变量
- node.js - 节点 cron 只执行指定日期,执行成功后完全停止
- java - 使用 SPOON 创建匿名类的实例
- linux - curl在bash中将双引号替换为单引号
- python-3.x - 从 .py 转换为 .exe 但不显示输出图
- azure - 如何使用 Azure Logic App 从基于会话的队列中读取具有会话 ID 的消息
- android - Android:引起:java.lang.RuntimeException:java.io.IOException:无效常量类型:19 at 5