[英]How to wait correctly for all async functions triggered in a sync loop to return a value - JS
I have an async operation in a loop which fetches a result and pushes to an array like this: 我在循环中有一个异步操作,该操作可获取结果并推送到这样的数组:
arr = [] while (some_limit_reaches) { async_operation(arg, function(err, data) { if (!err) arr.push(data) }) } // now arr is not completely filled until all async // operations are finished in the loop above
the problem is that array is not completely filled until all async operations are done, how can I have a fully filled array after loop is over without using setTimeout? 问题是直到所有异步操作完成后数组才被完全填充,循环结束后如何在不使用setTimeout的情况下如何完全填充数组?
You're trying to make a an asynchronous operation synchronous. 您正在尝试使异步操作同步。 You need to check if your desired state is true in your asynchronous callback. 您需要检查异步回调中所需的状态是否为true。 Try something like this. 尝试这样的事情。
while (some_limit_reaches) {
async_operation(arg, function(err, data) {
if (!err)
arr.push(data);
if(check_if_the_array_is_full){
//Call some function that continues your operation
}
})
}
This way your processing won't continue until all the array is full. 这样,直到所有阵列都装满后,您的处理才会继续。
This solution is a little bit verbose, but respects the separation of tasks. 这个解决方案有点冗长,但是尊重任务的分离。 Its schema is similar to kriskowal's q.all
. 它的架构类似于kriskowal的q.all
。
var arr = [], limit = 10, i=0, terminated_operations = 0;
while (i < limit) {
async_operation(arg, function(err, data) {
if (!err) {
arr.push(data);
operationTerminated(arr);
}
});
}
function operationTerminated(data) {
terminated_operations++;
if( terminated_operations === limit - 1) {
doStuff(data);
terminated_operations = 0;
}
}
function doStuff(data) {
console.log('all data returned', data);
}
The first snippet represents the core logic. 第一个片段代表核心逻辑。 The second function is only a trigger of the action declared in the third one. 第二个函数只是第三个函数中声明的动作的触发器。
Edit: 编辑:
In order to answer at the original question in the title 为了回答标题中的原始问题
How can I make sure that an async operation does not keep array in my code empty? 如何确保异步操作不会使代码中的数组为空?
I recommend to return data=undefined
in case of async_operation
failure, so you can accept also []
as valid return value and keep higher control in core logic. 我建议在async_operation
失败的情况下返回data=undefined
,因此您也可以接受[]
作为有效的返回值,并在核心逻辑中保持较高的控制权。 This way you can rewrite the loop as: 这样,您可以将循环重写为:
while (i < limit) {
async_operation(arg, function(err, data) {
if(err) {
console.error('error occurred', err);
break;
}
if(data) {
arr.push(data);
operationTerminated(arr);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.