Search code examples
javascriptnode.jsecmascript-6es6-promise

Promise in foreach loop


I have some struggles with a foreach loop. This is my situation: I have some elements in an object array. I need to perform 2 queries per object. Than I need the next object and do the same etc.

I have made 2 methods for the query:

function insertObj(locationId, cartId, quantity){
        return models.orders_cart.create({
            quantity: quantity,
            cartId: cartId,
            locationId: locationId,
        });
    }

function insertObj2(locationId, cartId, quantity){
    return models.orders_cart.create({
        quantity: quantity,
        cartId: cartId,
        locationId: locationId,
    });
}

.create returns a promise, so I can use then. This is my foreach loop.

locations.forEach(function (element) {

});

I need both methods in there. Waiting on the result and go to the next iteration. I really don't know how to do it properly with promises.


Solution

  • If you can use async-await this will do the trick:

    async runAsync(locations){
      for(let location of locations){
        await something();
        await something1();
      };
    }