forEach

时间:2016-05-20 08:13:50

标签: javascript node.js promise

我正在尝试使用promise(Q)重写我的项目的代码。 我不知道如何在foreach循环中获取一系列promise的结果:

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

我看到每次日志都标记一个空数组,那我该如何解决?

4 个答案:

答案 0 :(得分:4)

你应该永远return all promises,而你忘了在这里的几个地方。

如果可以使用=>箭头函数,然后这些隐式返回,这避免遗忘。

使用forEach并将结果返回到数组中,而不是忽略返回值的map。这也是并行工作:

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

这里的嵌套是有意的,可以一起访问res1res2

答案 1 :(得分:1)

这个怎么样?

0 =>
object(stdClass)[2924]
  public 'price' => string '100.000'
  public 'name' => string 'Standard ticket'
  public 'available_tickets' => string '98'
1 =>
object(stdClass)[2972]
  public 'price' => string '150.000'
  public 'name' => string 'Luxus ticket'
  public 'available_tickets' => string '50'

答案 2 :(得分:0)

这样的事情是你需要的吗?

tableView

答案 3 :(得分:0)

Array.map()Q.all()

结合使用
var resProducts = [];

Q.all(products.map(function (currProduct) {
        // Return promise that Q.all() can resolve.
        return Stock.saveNewStock(currProduct)
            .then(function (res1) {
                // Make sure you always return promises when they
                // are in a chain so  the chain will work correctly.
                return Product.saveNewProduct(currProduct)
                    .then(function (res2) {
                        resProducts.push(res2);
                        return Product.addStockToProduct(res1, res2)
                    })
            })
    }))
    .then(function (products) {
        // Products here is the array of resolved promises.

        // and here your array will be full.
        console.log(resProducts);
    })
    .catch(function (err) {
        console.log(err)
    });