ForEach 函数不对每个对象执行操作,仅执行一次

ForEach function not performing actions on each object, only once

我正在为纸牌游戏构建一个套牌构建应用程序,我还有一个数据库设置,用于销售我玩过的这些纸牌,这个套牌构建器有效地允许我从可销售库存中提取库存(即如果我有 1 张 x 卡,并将其添加到一副牌中,它会将数据库中该项目的 countInStock 设置为比原来少 1。)但是当我删除整个 {deck}我需要将 [deck.cards] 中的所有内容重新播种到可售库存中,这是一个 {Card} 对象的数组,我试图简单地遍历该数组中的每个对象,找到那张卡片,找到产品在数据库中,将产品设置为 +1(因为每张卡,可以是同一张卡,但它将是不同的对象)因此我只需要将 countInStock 增加 1,当我到达此端点时,它会放回库存 1 个对象,但它似乎会忽略 forEach 循环中的其他对象,并且不会向库存中添加更多对象,我不确定为什么它会工作一次,但它不会在每次迭代中工作n.

代码:

/**
 *  @description  This function removes a deck from the database, and re-seeds whatever cards where in that deck
 *                back into the sellable stock
 *
 *  @route        DELETE /api/deck/:deckId
 *  @param        deckId ObjectID of the deck
 *  @comment      hitting this route will change the countInStock value of the {product}
 *                in the database by whatever cards where in the [deck.cards]
 *
 */
module.exports = asyncHandler(async (req, res) => {
  try {
    // find the deck
    const deck = await Deck.findById(req.params.id);
    // check if it exists
    if (!deck) {
      return res
        .status(404)
        .json({ message: `Deck: ${req.params.id} cannot be found` });
    }

    // we need to run a foreach command over every object in [deck.cards]

    await deck.cards.forEach(async (c) => {
      console.log(c);
      // find the card
      const card = await Card.findById(c._id);
      // We then need to find the sellable { Product } and add back to it, so it can be sold/traded
      const product = await Product.findById(card.productId);
      // increase the amount of inStock sellable items, by 1.
      await product.set({ countInStock: product.countInStock + 1 });
      await product.save();
      // if we get here we want to remove the card object from the database, its just a placeholder.
      await card.remove();
    });

    // remove the deck
    await deck.remove();
    res.status(200).json({ success: true });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: `Server Error: ${error.message}` });
  }
});

我会尽量描述@jfriend00给出的解释。

包括我在内的许多人都认为 forEachfor 循环的简化版本,但当谈到 async await 时,事实是 IT IS NOT。例如,让我们看这段代码:

const loopThis = [1, 2, 3, 4];

function timeOut2000() {
  return new Promise(resolve => setTimeout(resolve, 1000));
}

async function loopThrough() {
  await loopThis.forEach(async x => {
    await timeOut2000();
    console.log(x)
  });
}

loopThrough()

上面的运行时,我们可以看到它不会在每个循环中等待timeOut2000,因为它不会等待每个promise的解析。

要实现每个循环的async await,我们可以使用for循环或for .. in ..,如下所示:

const loopThis = [1, 2, 3, 4];

function timeOut2000() {
  return new Promise(resolve => setTimeout(resolve, 1000));
}

async function loopThrough() {
  for (const x of loopThis) {
    await timeOut2000();
    console.log(x)
  };
}

loopThrough()