Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async method, Iterator should be happend when update is happend

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);                     

});
like image 495
Muthukumar Marichamy Avatar asked Nov 09 '22 08:11

Muthukumar Marichamy


1 Answers

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);
});
like image 159
Denis Lisitskiy Avatar answered Nov 15 '22 06:11

Denis Lisitskiy