使用Javascript 在for循环||中修改后得到数组的结果.forEach ||换吗?
问题是javascript以异步方式运行所有内容,因此我找不到解决这个看似简单问题的方法。
示例:
action: function () {
modelsResult = [];
Model.forEach(function (model) {
doSomething(model, function (newModel) {
modelsResult.push(newModel);
});
response.send({
models: modelsResult
});
}
var doSomething = function (model, callback) {
model.id = model.id++;
callback(model);
}
在modelResult拥有forEach提供的所有模型之前, response.send
将被执行。但是,如果我将response.send
放在forEach中,那么同样会发生。
答案 0 :(得分:2)
如果doSomething是异步的,那么您将不得不重新调整代码。您不能使用异步操作编写顺序代码,并希望事情遵循顺序路径。他们根本就没有。
相反,您必须构建代码,以便了解上次异步doSomething()
操作何时完成,然后,只有这样,您才能使用所有结果执行response.send()
异步操作。
我不知道您的代码中究竟有Model
是什么,但如果我们可以提前知道调用.forEach()
会有多少次迭代,那么您的代码可能是这样实现:
action: function () {
modelsResult = [];
// create a count of remaining iterations
var cntRemaining = Model.length;
Model.forEach(function (model) {
doSomething(model, function (newModel) {
// save results of this async operation
modelsResult.push(newModel);
// one more async operation has completed
--cntRemaining;
// if all async calls are done, then process the final result
if (cntRemaining === 0) {
response.send({models: modelsResult});
}
});
});
}
var doSomething = function (model, callback) {
++model.id;
callback(model);
}
答案 1 :(得分:1)
很多lib可以帮助你解决这个问题。或者你可以在函数中编写自己的小布尔值,只有当索引与长度相同时才会设置,从而开始你的最终回调...保存工作虽然有用的东西;我建议看看Q或下划线,有很多不同的方法来实现这一点。
https://github.com/kriskowal/q http://underscorejs.org/#after