gpt4 book ai didi

node.js - 在array.foreach Sequelize 中查询数据库

转载 作者:行者123 更新时间:2023-12-03 22:26:28 25 4
gpt4 key购买 nike

使用 array.forEach 修改来自 sequelize 的结果集。

我想遍历返回的购物车,访问每个元素的数据库并添加一些属性并返回。

const promiseInvoices = [];

await ShoppingCart.findAll({
where: {
// eslint-disable-next-line object-shorthand
cart_id: cartItem.cart_id,
},
}).then(result => {
result.forEach(cartItem2 => {
const prod = Product.findByPk(cartItem2.product_id);
console.log(prod);

let cartItem3 = {};
const total = prod.price * cartItem2.quantity;
cartItem3.cart_id = cartItem2.cart_id;
cartItem3.product_id =cartItem2.product_id;
cartItem3.attributes =cartItem2.attributes;
cartItem3.quantity =cartItem2.quantity ;
cartItem3.price = prod.price;
cartItem3.name = prod.name;
cartItem3.image = prod.image2;
cartItem3.item_id = cartItem2.item_id;
cartItem3.subtotal = total;

return promiseInvoices.push(cartItem3);
});
});

返回shoppingCart,访问每个shoppingcart 对象的数据库并获取产品以填充每个shoppingCart 项目的值。对 Product.findByPk 的调用返回一个可用的 promise,如下所示:
Promise [Object] {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined }

最佳答案

  • 所有 Sequelize CRUD 调用都是异步的,这意味着它们返回一个 promise,因此您必须对它们进行 await。返回 Promise 对象而不是带有详细信息的产品的原因是因为您没有等待 findByPk 调用完成。
  • forEach 结构不支持异步操作。即使您使 array.forEach 回调异步,它也不会工作,并且仍然返回 Promise 对象而不是带有详细信息的产品。

  • 要解决此问题,您需要等待异步 findByPk 调用并使用支持异步操作的循环。您可以将 for...of 循环用于您的用例。
    const promiseInvoices = []

    await ShoppingCart.findAll({
    where: {
    cart_id: cartItem.cart_id
    }
    }).then(result => {

    // for...of loop that supports await
    for await (const cartItem2 of result){
    // Make sure to wait on all your sequelize CRUD calls
    const prod = await Product.findByPk(cartItem2.product_id)

    // It will now wait for above Promise to be fulfilled and show the proper details
    console.log(prod)

    let cartItem3 = {}
    const total = prod.price * cartItem2.quantity
    cartItem3.cart_id = cartItem2.cart_id
    cartItem3.product_id = cartItem2.product_id
    cartItem3.attributes = cartItem2.attributes
    cartItem3.quantity = cartItem2.quantity
    cartItem3.price = prod.price
    cartItem3.name = prod.name
    cartItem3.image = prod.image2
    cartItem3.item_id = cartItem2.item_id
    cartItem3.subtotal = total

    // Simple push will work in this loop, you don't need to return anything
    promiseInvoices.push(cartItem3)
    }
    })

    关于node.js - 在array.foreach Sequelize 中查询数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58714698/

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