当每个函数结束时需要执行函数

我有节点js / firebase中的这个代码:

ref.child("recipts").once("value", function(usersSnap) { usersSnap.forEach(function(reciptsSnap) { reciptsSnap.forEach(function(reciptSnap) { reciptSnap.ref.child("last_recipt").once("value", function(b) { b.forEach(function(c) { //Here I fill some "product" object }); }); reciptSnap.forEach(function(b) { //Here I fill some "product" object }); }); }); }); 

当“reciptSnap”forEachs完成时,我需要执行一个函数。 我怎样才能做到这一点,我尝试使用variablesi ++和i–但只适用于每个迭代。 我调用的函数是用forEachs循环中的填充数据操纵我创build的产品对象。

如果我理解正确,你想在reciptsSnap.forEach完成时调用一个函数,它里面的所有asynchronous任务也完成了。

为了达到这个目的,你可以使用index参数和传递给forEach的callback函数的原始数组。 ( 见文档

代码将如下所示:

注意下面的代码没有改变当前使用的forEach循环结构,但是使用Promise或者async重写代码会是更好更干净的方法 )。

 var loop1Done = false; var loop2Done = false; ref.child("recipts").once("value", function (usersSnap) { usersSnap.forEach(function (reciptsSnap) { reciptsSnap.forEach(function (reciptSnap, index, colA) { const idx = index; const col = colA; reciptSnap.ref.child("last_recipt").once("value", function (b) { const i = idx; const c = col; b.forEach(function (c, j, colB) { //Here I fill some "product" object // Do what you want here // Check if all done for this loop if ((j >= colB.length) && (i >= c.length)) { loop1Done = true; // Check if all loops done if (loop1Done && loop2Done) { // Call final callback function // eg myFinalCallback(); } } }); }); reciptSnap.forEach(function (b, k, colC) { //Here I fill some "product" object const i = idx; const c = col; // Do what you want here // Check if all done for this loop if ((k >= colC.length) && (i >= c.length)) { loop2Done = true; // Check if all loops done if (loop1Done && loop2Done) { // Call final callback function // eg myFinalCallback(); } } }); }); }); }); 

尝试:

  reciptSnap.child("last_recipt").forEach(function(b) { b.forEach(function(c) { //Here I fill some "product" object }); }); 

这应该起作用,因为当您在收据节点上执行“值”操作时,您的所有数据都应该已被提取。

如果这样做,你的代码不再是asynchronous的,在最后一个forEach之后,你可以执行你想要的function。

  reciptSnap.forEach(function(b) { //Here I fill some "product" object }); //Execute your function here });