![](/img/trans.png)
[英]How to run code after separate ajax calls have completed within an each loop
[英]How to Send response after for each loop completed
Response.json 应在 foreach 循环完成执行后执行
var todoarr = (req.body.data) ? req.body.data : undefined todoarr.forEach(function(element) { if(element.done == true) { TodoService.removeTodo(element, function(success) { }); } }); res.json("success");
你可以尝试使用 async.js http://caolan.github.io/async/ 。
each
方法http://caolan.github.io/async/docs.html#each
或者你可以尝试使用Promise.all
。
例如:
let promiseArr = [];
todoarr.forEach(function(element) {
if(element.done == true) {
promiseArr.push(somePromiseMethod(element));
}
});
//now execute promise all
Promise.all(promiseArr)
.then((result) => res.send("success"))
.catch((err) => res.send(err));
更多信息在这里。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
一些承诺示例:
function somePromiseMethod(element) {
return new Promise((resolve,reject) => {
TodoService.removeTodo(element, function(success) {
resolve();
});
});
}
希望这会有所帮助。
您不能对单个请求发送多个响应,您唯一可以做的是带有结果数组的单个响应:
es 与异步:
const async = require('async')
// FIX ME: this isn't correctly handled!
const todoarr = (req.body.data) ? req.body.data : undefined
let results = []
async.each(todoarr, function(element, callback) {
console.log('Processing todo ' + element)
if(element.done == true) {
TodoService.removeTodo(element, function(err, success) {
if(err){
callback(err)
} else {
results.push(success)
callback(null, success)
}
})
}
}, function(err) {
if(err) {
console.log('A element failed to process', err)
res.status(500).json(err)
} else {
console.log('All elements have been processed successfully')
// array with the results of each removeTodo job
res.status(200).json(results)
}
})
您可以在forEach
的回调函数中发送响应。
修改您的函数,使其仅在最后一次迭代时调用res.json()
。
示例:
var todoarr = (req.body.data) ? req.body.data : undefined
todoarr.forEach(function(element,index) {
if(element.done == true) {
TodoService.removeTodo(element, function(success) {
});
}
if(index==todoarr.length-1){
res.json("success");
}
});
但是,它可能不符合编码标准,但绝对可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.