Javascript JS中的承诺循环
我试图在nodejs中的for循环中运行查询,for循环的每个迭代都运行一个查询。查询是通过返回承诺的“get()”方法完成的。在我的函数(包含此for循环)中,我将返回get()方法返回的承诺,如下所示:Javascript JS中的承诺循环,javascript,promise,async-await,parse-server,Javascript,Promise,Async Await,Parse Server,我试图在nodejs中的for循环中运行查询,for循环的每个迭代都运行一个查询。查询是通过返回承诺的“get()”方法完成的。在我的函数(包含此for循环)中,我将返回get()方法返回的承诺,如下所示: for(var i=0;i{/*在所有查询返回结果后执行操作*/}) 两种可能性,并行和串行。我将展示这两个方面: async function serial(productIds) { for(const productId of productIds) { await q
for(var i=0;i
但这会在第一次迭代后返回,并且不会在其余的迭代中继续。我如何解决这个问题
在上下文中,我使用的是Parse的云函数。您必须建立这样的承诺链:
let chain = Promise.resolve();
for (i=0; i<1000; i++) {
chain = chain.then(()=>queryObject.get(objectId))
}
chain.then(()=>{ /* do something once all queries have returned a result */})
let chain=Promise.resolve();
for(i=0;iqueryObject.get(objectId))
}
然后(()=>{/*在所有查询返回结果后执行操作*/})
两种可能性,并行和串行。我将展示这两个方面:
async function serial(productIds) {
for(const productId of productIds) {
await queryObject.get(productId).then(//handle result)
}
}
function parallel(productIds) {
return Promise.all(
productIds.map( productI => queryObject.get(productId).then(//handle result)
);
}
TLP给出的答案证明了这一点,并将在这里对您起作用。不过,我将对正在发生的事情进行更多的解释,并提供另一个答案 首先,让我们了解为什么您的代码无法实现您想要的功能:
for(var i=0; i < productIds.length; i++) {
return queryObject.get(productIds[i]).then(//handle result)
}
同样,您的代码相当于:
return productIds[0];
return queryObject.get(productIds[0]).then(//handle result)
假设你在这里看到了错误,现在我将指出你的思维过程中的一个小错误。在你的帖子里你说:
我返回get()方法返回的承诺,如下所示:
您引用了从“the”调用get()方法返回的一个承诺,但实际上您希望多次调用get()方法,从而产生许多承诺
如果所有这些都有意义,那么您的下一步就是决定是否:
for(var i=0; i < productIds.length; i++) {
queryObject.get(productIds[i]).then(//handle result)
}
for(var i=0;i
分享更大的代码片段。我不在计算机atm机旁,但我很乐意回答您稍后回来的任何疑问,并分享更多代码。为什么异步等待标记我已更新了问题,希望它能给您提供更多的信息。我会尝试一下,让您知道。谢谢我尝试了这个方法,它按顺序获取每个产品,但我调用它的主方法在for循环的第一次迭代后继续执行。如何使主函数仅在serial()函数完成所有查询后才继续执行不确定为什么有人否决了此项。。。请解释一下,我想这应该行得通。我将尝试这两种方法,并向您提供最新信息
for(var i=0; i < productIds.length; i++) {
queryObject.get(productIds[i]).then(//handle result)
}