我有对象数组,我必须对array的每个元素执行异步操作。但是当我使用 Async.series()函数时,它在异步调用中有一些冲突在函数之间。请通过 async.map()函数建议一些操作。
function(cb){
var bookings = payload.bookings;
for(var i=0;i<bookings.length;i++){
var dataToSave = {};
//service choosen by customer
var service_id = bookings[i].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);
}
} else {
cb(ERROR.NO_SERVICE_PROVIDERS_FOUND);
}
console.log("dataToSave 1",dataToSave);
}
});
}
},
function(cb) {
cb();
}
输出:
dataToSave 2 { serviceId: '578e0da7c8c4cfc807040852' }
dataToSave 1 { serviceId: '578e0da7c8c4cfc807040852',
serviceProviderList:
[ { id: 578e18f6ed564791083c75ad, serviceRate: 200 },
{ id: 578e1996ed564791083c75b4, serviceRate: 200 } ] }
预期产出:
dataToSave 1 { serviceId: '578e0da7c8c4cfc807040852',
serviceProviderList:
[ { id: 578e18f6ed564791083c75ad, serviceRate: 200 },
{ id: 578e1996ed564791083c75b4, serviceRate: 200 } ] }
dataToSave 1 { serviceId: '578e0da7c8c4cfc807040852',
serviceProviderList:
[ { id: 578e18f6ed564791083c75ad, serviceRate: 200 },
{ id: 578e1996ed564791083c75b4, serviceRate: 200 } ] }
请使用 async.map()来推荐一些操作,以便我可以单独执行每项操作。