首页 > 解决方案 > 无法使用 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但得到相同的结果。

标签: node.jsasynchronous

解决方案


医生

将函数 iteratee 并行应用于 coll 中的每个项目。使用列表中的项目调用 iteratee,并在完成时回调。如果迭代者将错误传递给它的回调,主回调(对于每个函数)会立即使用错误调用。

请注意,由于此函数将 iteratee 并行应用于每个项目,因此无法保证 iteratee 函数将按顺序完成。

我想couponHandler.checkIFWalletExists您的代码中没有注释掉该方法。这意味着迭代器将在完成第一个项目的处理之前开始处理第二个项目。并且可能是因为第二个项目的处理速度更快,您会看到结果顺序错误。


推荐阅读