0

我有一张order桌子,我想“再次购买”,该order桌子包含一列productDetails。在这个专栏里面,我有一个数组products

要执行此“再次购买”操作,我需要将相同的数组放入我的购物车中。及时更新重要信息(检查是否有库存,产品是否在目录中处于活动状态等),对于数组中的每个产品,我将在我的购物车表上进行更新,基本上,我将尝试以下操作:

我正在使用node.jssequelize.js执行此操作:

// Get the older order
const order = await Order.findOne({
    include: [
        {
            model: OrderProduct,
        },
    ],
    where: {
        orderId,
    },
});

// If the cart have something inside, clean the cartDetails column
await CartService.clean(order.userId);

// The addProduct do the checks and insert the product inside the cart
await Promise.all(
    order.OrderProducts.map(async data => {
        await CartService.addProduct(order.userId, data.productMarketId, data.quantity);
    })
);

也许,他们addProduct只插入一种产品。如果我们有更多,地图会正确执行,但只会在列表中添加一个产品。

当我在调试时运行时,首先代码调用两次(当我的订单上有两个产品时)addProduct(),获取购物车数据的选择总是为空,只有最后一个产品被正确插入。

2 种产品的预期行为:

1. clean cart
2. enter on iterator (map or something else) (product 0):

  2.1. Select cart details (which is empty on first time)
  2.2. Insert product on cart

3. next item on iterator (product 1)

  3.1. Select cart details (which have one element)
  3.2. Insert product on cart

3. end of iterator with 2 products registered on my database.

发生了什么:


1. clean cart
2. enter on iterator (map or something else):
  2.1.a. get the empty cart
  2.1.b. get the empty cart again
  2.2.a. update the product 0 on empty cart selected in 2.1.a. (following the stack of (a)
  2.2.b. update the product 1 on empty cart selected in 2.1.b. (following the stack of (b)

3. Return the cart with only one product inside (the last product).

编辑:我做了一个关于行为的视频:视频在这里

并且有原始的 addProduct 函数(它使用async)并首先并行化await(我放在/* ... */一些地方以使问题更小):

  async addProduct(userId, productMarketId, quantity) {
        const productMarketData = await productMarket.findByPk(productMarketId, { /* ... */ });

        const productKey = Buffer.from(PHPSerialize.serialize(`SP_${productMarketId}`)).toString('base64');

        /* ... */

        const cart = await Cart.findOne({ /* ... */ });

        if (!cart) {
            cart = await this.clean(userId);
        }

        /* ... */

        const newCart = await Cart.upsert({ /* ... */ }).then(result => {
            return result.cartUserId;
        });
        return newCart;
    }

这种行为与承诺有关吗?还是异步/等待行为?谢谢。

4

1 回答 1

1

Array.map 不适用于异步函数,因此您应该将 Promise.all 调用修改为如下内容:

await Promise.all(
    order.OrderProducts.map(data => {
        return CartService.addProduct(order.userId, data.productMarketId, data.quantity);
    })
);

或者

顺序版本

for (const orderProduct of order.OrderProducts) {
  await CartService.addProduct(order.userId, orderProduct.productMarketId, orderProduct.quantity)
}
于 2020-05-12T18:53:26.273 回答