返回Promises而不是Async

时间:2017-02-09 03:54:18

标签: javascript ecmascript-6 promise

我想返回看起来像这样的数据

[
  shops: {
    id,
    products:[{Object}, {Object}]
  },
  shops: {
    id,
    products:[{Object}, {Object}]
  } 
]

所以我有商店ID列表,我需要迭代并获取每个商店的产品并附加它然后返回。

我就是这样做的

const shops = response.data
const respToSend = []
async.eachSeries(shops, (shop, callback) => {
  const id = shop.shop_id
  const shopObj = {
    id
  }

  // Fetch products of each Shop.
  getProductList(id)
    .then((responseData) => {
      shopObj.products = responseData.data.products
      respToSend.push(shopObj)
      callback()
    })
    .catch(() => {
    })
}, () => {
  return respToSend
})

正如您所看到的,我正在使用异步节点模块来执行异步任务,但是应用程序要求我将响应作为Promises返回,然后将解析,否则它将打印为null。如何使用承诺实现这一目标?我是新来的承诺,对任何错字都很抱歉。

1 个答案:

答案 0 :(得分:2)

尝试Promise.all(iterable)

Promise.all(shops.map(shop => getProductList(shop.shop_id)
    .then(products => ({id: shop.shop_id, products}))
    .then(/* actions for each shop */))
  .then(shops => {
    /* actions for array of shop objects */
    respToSend = shops;
  })