javascript - 使用foreach遍历调用异步函数,返回结果请求不正常?
问题描述
<!-- begin snippet: js hide: false console: true babel: false -->
async function query(num) {
let data = await request(url, {num})
console.log(num, data)
}
[1, 2].forEach(function(item){
let _self = this
(function(item) {
setTimeout(() => {
_self.query(item)
console.log(item)
}, i)
})(item)
})
// if the server response
server.get('*', function(req, res) {
let num = req.num
res.send(num)
})
异步查询响应为: // 1, 2 // 2, 1
但是期望响应是 // 1, 1 // 2, 2 我怎样才能得到想要的结果?请求参数如何与返回结果一致?
解决方案
听起来您想串行执行查询,而不是并行执行。所以,每次迭代的开始都应该等到前一次迭代的分辨率才开始。await
与for..of
或一起使用reduce
。您不能与forEach
.
const requests = [1, 2];
const resolveWithArg = function(arg) {
return new Promise(res => setTimeout(() => {
console.log('resolving with ' + arg);
res(arg);
}, 1000))
}
requests.reduce(async(lastPromise, arg) => {
// the reducer function isn't actually running sequentially itself, it's that they all run immediately, but await the resolve of the previous iteration on the first line
await lastPromise;
const result = await resolveWithArg(arg);
console.log('got result ' + result);
}, Promise.resolve());
推荐阅读
- swift - 从 Xcode Swift MacOS 项目创建 pkg
- haskell - 如何隐藏元组类型构造函数?
- angular - 为什么 @ViewChild() 装饰器在使用 PrimeNG FullCalendar 的这个 Angular 组件中不起作用?
- python - 如何从 Django 内置 API 文档中排除 rest-auth 端点?
- reactjs - material-ui 自动完成接受自定义值
- c++11 - 不知道如何反映 oneof 归档
- googletest - 如何在谷歌测试中使用 QAbstractItemModelTester?
- javascript - 工作流程如何将一个子模块 typescript 写成一个非 typescript 模块?
- c++ - 使用表达式-SFINAE 的函数模板的类定义
- java - 如何通过带有@annotation 的 Open Api 3.0 描述我的对象的模式?