返回承诺而不是异步 [英] Return Promises instead of Async

查看:132
本文介绍了返回承诺而不是异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to return data which will look something like this

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

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

So I have list of shop ids on which I need to iterate and get the products for each shop and append it and then return.

这是我如何做的

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返回响应解决否则打印为零。如何使用承诺实现这一点?我很抱歉对任何打字错误承诺。

As you can see that I am using async node module for doing the async task but the application requires from me to return response as Promises which will then be resolved otherwise it prints null. How can I achieve this using promises? I am new to promises so sorry for any typo.

推荐答案

尝试 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;
  })

这篇关于返回承诺而不是异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆