简体   繁体   English

如何在for循环节点js中调用asyn函数

[英]How to call asyn function inside for loop Node js

I want to call async.parellel([],function(){}) inside a for loop. 我想在for循环中调用async.parellel([],function(){}) When i tried the for loop completes execution before the async function execution.How to resolve this problem. 当我尝试for循环在异步函数执行之前完成执行。如何解决此问题。

You cannot solve the problem, for it is not a problem, it is how async functions work. 您无法解决问题,因为这不是问题,而是异步函数的工作方式。

If you start a bunch of async functions during the loop, the latter executes as a whole and puts the formers on the loop to be executed once it releases the control of the flow. 如果在循环过程中启动了一堆异步函数,则后者将整体执行,并在释放流程控制后将前者放在循环中执行。

Because of that, you'll see probably the function containing the loop terminates before the async functions start. 因此,您可能会看到包含循环的函数在异步函数启动之前终止。

The usual approach to give a response to the caller once all the async functions have terminated is by using a callback function as a parameter of the one that contains the root, thus nicely handle the async ones and invoke the callback once all of them have returned. 一旦所有异步函数都终止,对调用者做出响应的通常方法是使用回调函数作为包含根函数的回调函数的参数,从而很好地处理异步函数,并在所有它们都返回后调用回调。

I agree with Yelizaveta Gagarina. 我同意Yelizaveta Gagarina。

You can do some stuff like that if you want to work with your for loop: 如果要使用for循环,可以执行以下操作:

var fns = [];

for (var i = 0; i < 9; i++) {
  fns.push(function(callback){
     // do stuff here and call your callback with or without error
     callback(null, stuff); // no err in this example
  });
}

async.parallel(fns, function(err, stuff){
    if(err) return cb(err); // in this example err is null
    // do stuff, call next middleware if you are in this case
    next();
});

There is also async.series if you want to execute some functions 1 per 1. Hope this helps you. 如果要执行每1个功能中的一些功能,则还有async.series。希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM