node.js - 无法使用 async.each() 异步迭代具有异步块的数组
问题描述
我有一些异步功能,我想为数组中的每个元素执行currencyData
如下所示。我有以下逻辑 -
exports.getCurrenciesOfMerchant(req,res,function(currencyData)
{
async.each(currencyData, function (eachCurrency) {
fieldObject.currencyId=eachCurrency;
console.log("See currencyData "+fieldObject.currencyId);
//async block starts here
couponHandler.checkIFWalletExists(res,fieldObject,function(fieldObject)
{
console.log("checked wallet for curr "+fieldObject.currencyId);
if(fieldObject.hasWallet == 0)
{
exports.createWalletForUser(fieldObject,res,function(fieldObject,res){
// exports.createCoupon(fieldObject,res,function(res,fieldObject,couponId){
// return exports.couponCreationResponse(res,fieldObject,couponId);
// });
console.log("created wallet");
});
}
});
});
});
以下是输出 -
See currencyData 5
See currencyData 6
checked wallet for curr 6
checked wallet for curr 6
created wallet
created wallet
可以看出,async.each() 在异步块完成执行之前取值 6。它从未真正运行过值 5 的逻辑。
我认为这是 async.each() 有用的地方。但是,我无法让它工作。尝试使用async.forEachOf
但得到相同的结果。
解决方案
医生说:
将函数 iteratee 并行应用于 coll 中的每个项目。使用列表中的项目调用 iteratee,并在完成时回调。如果迭代者将错误传递给它的回调,主回调(对于每个函数)会立即使用错误调用。
请注意,由于此函数将 iteratee 并行应用于每个项目,因此无法保证 iteratee 函数将按顺序完成。
我想couponHandler.checkIFWalletExists
您的代码中没有注释掉该方法。这意味着迭代器将在完成第一个项目的处理之前开始处理第二个项目。并且可能是因为第二个项目的处理速度更快,您会看到结果顺序错误。
推荐阅读
- linux - Linux如何查找命令删除多个文件?
- embedded-linux - 如何有条件地在 yocto bb recipe 中安装和发送文件?
- javascript - 如何在页面加载时突出显示垫树的几个节点?
- python - 为什么当我尝试在此网页上抓取 PDF 的链接时,我只得到一个空列表作为回报?
- python-3.x - 从 2D 图像进行 3D 对象定位
- sql - 日期范围到空日期
- excel - 格式化此 VBA 代码的正确方法是什么?
- java - firebase 数据库上的图片网址未显示正确的 http 网址“com.google.android.gms.tasks.zzu@1234567”
- python - 当我更改不应触发任何更新的按钮设置时,为什么我的绘图会被面板更新(两次)?(面板霍洛维兹)
- apache-spark - Spark:复制另一个表的聚合列 - withColumn