使用async.forEach对对象数组进行操作

时间:2016-07-20 06:29:53

标签: node.js asynchronous node-async

我是node.js的新手,我使用async.forEach()编写了代码。出了点问题我没有弄错。

async.forEach(payload.bookings,fun,function(err,res){
        var data ;
        if(err)
            console.log(err);
        if(res) {

            data = res;
            console.log(data);
        }
    });

    function fun(booking,cb){

        var dataToSave = {};

        //service choosen by customer
        var service_id = booking.serviceId;

        dataToSave.serviceId = service_id;

        var query = {
            services : {$elemMatch : { serviceId : service_id } }
        };

        var projection = {
            cellPhoneNumber :1,
            countryCode:1,
            services :1
        };

        var options = {};

        Service.serviceProvider.getServiceProviders(query,projection,options,function(err,data){

            if(err)
                cb(err);
            else{

                if(data && data.length>0){

                    //getting list of SP which gives the service name given by customer
                    dataToSave.serviceProviderList = [];

                    for(var sp=0;sp<data.length;sp++){

                        var serviceProvider = {};

                        serviceProvider.id = data[sp]._id;

                        //searching in services array of one particular service id
                        for(var j=0;j<data[sp].services.length;j++){

                            if(data[sp].services[j].serviceId==service_id)
                            {
                                serviceProvider.serviceRate = data[sp].services[j].rate;
                                break;
                            }
                        }
                        dataToSave.serviceProviderList.push(serviceProvider);
                    }
                    cb(dataToSave);
                }
                else{
                    cb();
                }
            }
        });
    };

输出:

{ serviceId: '578e0da7c8c4cfc807040852',
  serviceProviderList: 
   [ { id: 578e18f6ed564791083c75ad, serviceRate: 200 },
     { id: 578e1996ed564791083c75b4, serviceRate: 200 } ] }

预期产出:

{ serviceId: '578e0da7c8c4cfc807040852',
  serviceProviderList: 
   [ { id: 578e18f6ed564791083c75ad, serviceRate: 200 },
     { id: 578e1996ed564791083c75b4, serviceRate: 200 } ] }
{ serviceId: '578dca50e93da81f0423f6b6',
  serviceProviderList: [ { id: 578e18f6ed564791083c75ad, serviceRate: 100 } ] }

我看过swagger文档。当我点击试一试时,它会继续运行。它只显示我使用console.log打印的对象()

1 个答案:

答案 0 :(得分:1)

问题可能在于cb(dataToSave);行。回调模式为cb(err, results);。通过执行cb(dataToSave);,async.js认为您遇到了错误。

尝试将其更改为cb(null, dataToSave);

                    (...)
                    }
                    dataToSave.serviceProviderList.push(serviceProvider);
                }
                cb(null, dataToSave);
            }
            (...)