gpt4 book ai didi

javascript - 返回 Promise 而不是异步

转载 作者:行者123 更新时间:2023-12-01 04:01:56 28 4
gpt4 key购买 nike

我想返回如下所示的数据

[
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。我如何使用 promise 来实现这一目标?我对 Promise 很陌生,对于任何拼写错误,我深表歉意。

最佳答案

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

关于javascript - 返回 Promise 而不是异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42127919/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com