(JavaScript)使用里面的回调同步forEach循环 [英] (JavaScript) Synchronizing forEach Loop with callbacks inside

查看:219
本文介绍了(JavaScript)使用里面的回调同步forEach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在double forEach 中进行一些计算循环如下:

I am doing some computations inside a double forEach Loop something like this:

array.forEach(function(element){
    Object.keys(element).forEach(function(key){

        /* some complex computations with asynchronous callbacks  */        

    });
});

someFunctionHere();

在执行 someFunctionHere之前,Loop是否有办法先完成)功能?或者在继续 someFunctionHere() ...

Is there a way for the Loop to finish first before doing the someFunctionHere( ) function? or any way that the program will know if the Loop is finish before continuing to someFunctionHere( ) ...

之前程序将知道循环是否完成的任何方式我可能会错过一些论坛,但我找到的那些论坛并没有帮助我实现我想要实现的目标,而且我在NodeJS中这样做,我也在问是否有现有的库可以实现这一点。

I may be missing some forums but the ones I found did not helped me of what I want to achieve and by the way I am doing this in NodeJS , also I am asking if there are existing libraries that can make this happen.

我忘记添加此内容或者这是另一个问题吗?

是否有一种同步迭代的方法,它只会在当前迭代完成后进入下一次迭代? (对不起)

Is there a way to do the iteration synchronously that it will only proceed to the next iteration once the current iteration is done? (Sorry for this)

感谢您的帮助......

Thanks for any help...

推荐答案

看看async.js,特别是它的控制流程语句,例如每个 ,而直到

Take a look at async.js, and especially its control flow statements, such as each whilst and until.

使用async.js可以得到你想要的东西。

Using async.js you can get what you want to have.

在你的实际情况下你想要的是每个函数(以前称为 forEach ),分别为 eachSeries 函数不会并行运行单个迭代,而是串行运行(请参阅 eachSeries的文档详细信息)。

In your actual situation what you want is the each function (which has formerly been known as forEach), respectively the eachSeries function which does not run the single iterations in parallel, but in serial (see the documentation for eachSeries for details).

提供示例:

async.eachSeries([ 2, 3, 5, 7, 11 ], function (prime, callback) {
  console.log(prime);
  callback(); // Alternatively: callback(new Error());
}, function (err) {
  if (err) { throw err; }
  console.log('Well done :-)!');
});

这将遍历素数数组并以正确的顺序打印它们,一个接一个,最后打印出做得好: - )!

This will iterate over the array of prime numbers and print them in the correct order, one after each other, and finally print out Well done :-)!.

这篇关于(JavaScript)使用里面的回调同步forEach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆