JavaScript Result of a promise inside of forEach

I'm trying to rewrite the code of one my project with the promise (Q). I don't know how to take the result of a chain of promises inside a foreach loop:

var resProducts = [];
products.forEach(currProduct) {
     Stock.saveNewStock(currProduct)
        .then(function(res1) {
            Product.saveNewProduct(currProduct)
               .then(function(res2) {
                  resProducts.push(res2);
                  Product.addStockToProduct(res1,res2)
               })
         })
         .catch(function(err) {
             console.log(err)
         })
});
console.log(resProducts);

I see that every time the log stamps an empty array, so how I can resolve it?

Answer:1

You should always return all promises, and you're forgetting to in several places here.

If you can use => arrow functions, then these implicitly return, which avoids forgetting.

Instead of forEach which ignores return values, use map and return results into an array. This does the work in parallel as well:

Promise.all(products.map(product => Stock.saveNewStock(product)
  .then(res1 => Product.saveNewProduct(product)
    .then(res2 => Product.addStockToProduct(res1, res2)
      .then(() => res2))))
.then(resProducts => console.log(resProducts))
.catch(err => console.error(err));

The nesting here is intentional, to access res1 and res2 together.

Answer:2

How about this?

// Define iterator function
function doThingsWithProducts(productsLeft, resProducts) {
    if (productsLeft.length === 0) { return resProducts }
    else {
        var currProduct = productsLeft.shift(), res1, res2;
        return Stock.saveNewStock(currProduct)
        .then(function(res) {
            res1 = res;
            return Product.saveNewProduct(currProduct)
        })
        .then(function(res) {
            res2 = res;
            resProducts.push(res2);
            return Product.addStockToProduct(res1, res2)
        })
        .then(function() {
            return doThingsWithProducts(productsLeft, resProducts)
        })
        .catch(function(err) {
            console.log(err);
        })
    }
}

// resProducts is available in the result of the function
doThingsWithProducts(products, [])
.then(function(resProducts) {
    console.log(resProducts);
})
Answer:3

Something like this is that you need?

var defer = $q.defer();
            var promises = [];
            var resProducts = [];
            var errorCallback = function (e) {

              defer.reject();
            };

           products.forEach(currProduct) {

                promises.push(function () {
                    Stock.saveNewStock(currProduct)
                        .then(function(res1) {
                            return Product.saveNewProduct(currProduct)
                        .then(function(res2) {
                            resProducts.push(res2);
                            Product.addStockToProduct(res1,res2)
                   })
             })
             .catch(function(err) {
                 console.log(err)
             })
                }


                );
              }

            });
            return $q.all(promises);
Answer:4

I have an array of objects similar to the following block of code: var arr = [ { text: 'one', children: [ { text: 'a', children: [ ...

I have an array of objects similar to the following block of code: var arr = [ { text: 'one', children: [ { text: 'a', children: [ ...

  1. using array.prototype.find
  2. using array.prototype in javascript
  3. why use array.prototype
  4. use of array.prototype.slice.call

Wanted to use the 'uncover' effect on a slideshow but it seems that it doesn't work using jQuery Cycle 2. It is working fine using the old jQuery Cycle plugin. Please see code here $(function() { ...

Wanted to use the 'uncover' effect on a slideshow but it seems that it doesn't work using jQuery Cycle 2. It is working fine using the old jQuery Cycle plugin. Please see code here $(function() { ...

Write a function addArrays that takes 2 arrays of numbers as parameters and returns a new array where elements at same index position are added together. For example: addArrays([1,2,3], [4,3,2,1]); // ...

Write a function addArrays that takes 2 arrays of numbers as parameters and returns a new array where elements at same index position are added together. For example: addArrays([1,2,3], [4,3,2,1]); // ...

Is it possible to do this with html canvas? With this for (var i = 0; i < data.length; i += 4) { var grayscale = data[i]*0.2126 + data[i +1]*0.7152 + data[i +2]*0.0722; data[i] ...

Is it possible to do this with html canvas? With this for (var i = 0; i < data.length; i += 4) { var grayscale = data[i]*0.2126 + data[i +1]*0.7152 + data[i +2]*0.0722; data[i] ...