简体   繁体   English

如何正确等待同步循环中触发的所有异步函数返回值-JS

[英]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.

相关问题 如何使 for 循环等待所有异步函数完成。 异步函数里面有多个异步函数 - How to make for loop wait for all async functions to finish. async functions has multiple async functions inside in it 如何在节点 js 中同步异步函数 - How to make sync the async functions in node js 如何在JS中返回两个连续异步函数的值? - How to return value of both of the consecutive async functions in JS? JS 同步和异步 onclick 函数 - JS sync and async onclick functions 如果文件中的异步太多,nodejs如何等待所有代码完成并获取返回值 - nodejs how to wait all code done and get return value if too many async in the file 如何同时调用异步函数并等待所有回调? - How do I simultaneously call async functions and wait for all callbacks? 如何在node.js中等待N个异步函数完成,以便对它们的所有组合结果进行一些工作? - How to wait for N number of async functions to finish in node.js so that I can do some work on all their combined results? JavaScript在while循环中等待异步功能 - JavaScript wait for async functions in while loop 等待所有异步功能在jQuery中完成 - Wait for all async functions to complete in jQuery 如何等待所有异步任务在Node.js中完成? - How to wait for all async tasks to finish in Node.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM