I have an array which is being iterated using Asynch.forEachSeries. Inside the iterator I find the model and updated. I need to iterate the second item after update is happened. Find the code below.
async.eachOfSeries(stockUpdate, function (valueSU, keySU, callbackSU) {
ProductVariations.findOne({id:valueSU.id}).exec(function (ePV,dPV){
dPV.available_stock = parseInt(dPV.available_stock) - Qty;
dPV.save(function (errDPV) {
callbackSU(); // HERE ONCE, NEXT ITERATOR SHOULD BE CALLED
});
});
}, function (err) {
if (err) callback(err.message);
});
I think you should wrap "ProductVariations..." in promise. And wait, until it resolves. And then call next iterator.
This code must solve you task
let promiseProductVariations = function (valueSU, keySU) {
return new Promise(function (resolve, reject) {
ProductVariations.findOne({id:valueSU.id}).exec(function (ePV,dPV){
dPV.available_stock = parseInt(dPV.available_stock) - Qty;
dPV.save(function (errDPV) {
if(errDPV){
reject(errDPV);
}else{
resolve(); // HERE ONCE, NEXT ITERATOR SHOULD BE CALLED
}
});
});
})};
async.eachOfSeries(stockUpdate, function (valueSU, keySU, callbackSU) {
promiseProductVariations(valueSU, keySU)
.then(function () {
callbackSU();
})
.catch(function (error) {
if(error)
console.log(error);
//do thomething with error
});
}, function (err) {
if (err) callback(err.message);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With