nodejs for循环,调用asynch Mongo函数 - 但Mongo函数仅为最后一项调用X次

时间:2022-11-26 18:22:50

I have a case in which I am running a loop for n times, and for each loop call, I am to check the presence of a value in a couple of mongo collections say A, and B , and then upsert in a collection C

我有一个案例,我正在运行一个循环n次,并且对于每个循环调用,我要检查几个mongo集合中是否存在值A和B,然后在集合C中进行upsert

for (i=0;i<n;i++)
{
   Console.log("started call to doSomething for " + i);
   doSomething(i);
   Console.log("End call to doSomething for " + i);
} 

function doSomething(i)
{
  console.log("started doing something for " + i);
  calltoMongo(i);
}

function calltoMongo(i);
{
   common.db.collection.find(err,result)
  {
    console.log("here for " + i);
   common.db.collection.insert(<some object >);
  }
}

Above is just pseudo code of what I have, the output comes very crazy lets say i run it for 3 elements in my for loop

上面只是我所拥有的伪代码,输出非常疯狂让我说我在for循环中为3个元素运行它

the output would be

输出将是

started call to doSomething for 1
started doing something for 1
End call to doSomething for 1
started call to doSomething for 2
started doing something for 2
End call to doSomething for 2
here for 2
here for 2

I am at my wits end, I understand something funny happening due to scope resolution and that because only last element value remains when the loop ends, and the mongo side code starts working only after wards the value that remains in scope is the last value, But i don't know a way to fix it for real, even if I put sleep at end of call to Mongo function , it doesn't help.

我在我的智慧结束时,我理解由于范围解析而发生的一些有趣的事情,因为当循环结束时只剩下最后一个元素值,并且mongo端代码仅在保留范围内的值后才开始工作是最后一个值,但我不知道一种方法来解决它真实的问题,即使我在调用Mongo函数结束时进入睡眠状态,它也无济于事。

1 个解决方案

#1


You are creating a closure where each call to the function retains a reference to the stack frame containing i. Because the DB function is asynchronous it only runs once i has achieved its final value.

您正在创建一个闭包,其中每次调用该函数都保留对包含i的堆栈框架的引用。因为DB函数是异步的,所以只有在我达到最终值后才会运行。

Related

In terms of actually resolving your problem I would use promise chaining unless you need them to run in parallel.

在实际解决你的问题方面,我会使用promise chaining,除非你需要它们并行运行。

#1


You are creating a closure where each call to the function retains a reference to the stack frame containing i. Because the DB function is asynchronous it only runs once i has achieved its final value.

您正在创建一个闭包,其中每次调用该函数都保留对包含i的堆栈框架的引用。因为DB函数是异步的,所以只有在我达到最终值后才会运行。

Related

In terms of actually resolving your problem I would use promise chaining unless you need them to run in parallel.

在实际解决你的问题方面,我会使用promise chaining,除非你需要它们并行运行。