gpt4 book ai didi

javascript - 级联数组 promise 的正确方法( Mongoose 示例)

转载 作者:行者123 更新时间:2023-11-28 17:28:09 24 4
gpt4 key购买 nike

我需要了解使用 Mongoose 级联 promise 的正确方法。

我的函数 createCustomerBills 接收客户 ID 列表,对于每个客户 ID,我需要创建一个简单的账单。

这是代码:

const createCustomerBill = (customer) => {
return BillModel.create({
customer_id: customer.id,
value: 100
});
}

const createCustomerBills => (customerIds) => {
let criteria = {
_id: { $in: customerIds }
};

return CustomerModel.find(criteria)
.then(result => {
return result.map(customer => {
return createCustomerBill(customer);
}
})
.then(result => {
return CustomerModel.update(
{ _id: customer.id },
{ status: "BillCreated" }
);
});
}

步骤如下:1. 获取所有客户列表2. 为每个客户创建账单3. 对于创建的每个账单,更新客户状态

如果这是正确的方法以及可能的缺点,我需要建议。

最佳答案

因为您正在映射 CustomerModel.find 的结果,所以返回该数组不会等待 Promise 完成来运行下一个 .then,因为数组不是 Promise

这就是 Promise.all 的用武之地

此外,由于您需要单独更新每个账单,因此 promise 链的该部分需要位于 .map 迭代内

const createCustomerBill = customer => 
BillModel.create({
customer_id: customer.id,
value: 100
});

const createCustomerBills => customerIds => {
let criteria = {
_id: { $in: customerIds }
};

return CustomerModel.find(criteria)
.then(result =>
Promise.all(
result.map(customer => createCustomerBill(customer)
.then(result => CustomerModel.update({ _id: customer.id }, { status: "BillCreated" }))
)
)
)
.then(result => {
// all bills are now processed
});
}

关于javascript - 级联数组 promise 的正确方法( Mongoose 示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51072964/

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