Asynchronous method, Iterator should happen when update happens

I have an array that repeats using Asynch.forEachSeries. Inside the iterator, I find the model and update. I need to repeat the second item after the update. 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); }); 
+5
source share
1 answer

I think you should wrap "ProductVariations ..." in the promise. And wait until this is decided. And then call the next iterator.

This code should solve your problem.

 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); }); 
+1
source

All Articles