gpt4 book ai didi

javascript - 处理 Promise.all() 中每个 Promise 的响应对象

转载 作者:行者123 更新时间:2023-12-03 00:52:27 25 4
gpt4 key购买 nike

我有一个后端点,它创建客户并返回 userId 作为响应

例如

// Post Data
const customers = [{
firstName: 'John',
lastName: 'Smith',
userId: '12345
},
{
firstName: 'Phil',
lastName: 'Doe',
},
{
firstName: 'Dan',
lastName: 'Joe',
}
]


app.post('/customers', (req, res) => {
const arrayPromises = []
const customers = req.body.customers;
customers.forEach((customer) => {
//checking whether I have a userId already
if (!customer.userId) {
const postRequest = {
headers: Object.assign(res._headers, {
Accept: 'application/json',
'Content-Type': 'application/json',
}),
post:'www.createUserExample.com,
customer // post data,
};
arrayPromises.push(axios(postRequest))
//response will be {userId}
}
})


Promise.all(arrayPromises).then(result => {
//by this way I get all userids
res.status(200).json(result.data)
})


})

但是我需要发送一个包含 userIds 的响应对象

示例响应对象应该类似于

[{
firstName: 'John',
lastName: 'Smith',
userId: '12345'
},
{
firstName: 'Phil',
lastName: 'Doe',
userId: '65765'
},
{
firstName: 'Dan',
lastName: 'Joe',
userId: '786876'
}
]

因此,总的来说,我希望拥有客户的属性,并将创建的 userId 附加到发布数据对象并作为响应发送。

请让我知道最好的方法。我喜欢通过异步请求来创建客户

最佳答案

只需将已有 id 的对象插入数组即可。 (或对他们做出 promise )。然后,Promise.all 将生成您正在查找的数组。该数组不一定需要仅包含 API 请求的 promise :

const arrayPromises = []
const customers = req.body.customers;
customers.forEach((customer) => {
//checking whether I have a userId already
if (customer.userId) {
arrayPromises.push(Promise.resolve(customer));
} else {
arrayPromises.push(axios(…));
}
});

您还可以简化为

const arrayPromises = req.body.customers.map((customer) => {
//checking whether I have a userId already
return customer.userId
? Promise.resolve(customer)
: axios(…);
});

关于javascript - 处理 Promise.all() 中每个 Promise 的响应对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52994288/

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