繁体   English   中英

无法在 API 调用中的 forEach 循环中使用异步

[英]Unable to use async in forEach loop inside an API call

我有一个看起来像这样的 get API 调用

router.get('/review', async (req, res) => {
  try {
    const entity = await Entity.find();
    const entityId = [];
    Object.keys(entity).forEach((key) => {
      entityId.push(entity[key]._id);
    });
    const results = [];
    Object.keys(entityId).forEach(async (key) => {
      const reviews = await Review.find({ entityId: entityId[key] });
      results.push(reviews);
    });

    res.send(results);
  } catch (e) {
    res.status(500).send();
  }
});

entityId数组中,它有一个我需要的所有 id 的列表,直到它工作。 现在我想要做的是遍历entityId每个 id 并找到该实体具有的相应评论,将这些评论推送到results数组中并返回results

review有一个entityId字段,它与entity id相同。

我还看了 - Using async/await with a forEach loop

建议使用 for 循环,但它给出了以下错误。

iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.eslintno-restricted-syntax

我该如何解决这个问题?

forEach 不尊重 await,因此它可能会导致意外行为,您可以使用 map 从Review.find()返回 promise 数组并将它们包装在 await Promise.all({promises array here}) 中并在 Promise.all 上使用await 这将导致并行调用,而不是一个接一个地依次执行。

const promisesWoAwait = this.entityIds.map(entityId => Review.find({ entityId }));

const result = await Promise.all(promisesWoAwait);

使用承诺而不是 foreach。

你这个

const data = async () => {
  const entity = {
    a: { _id: "1231" },
    b: { _id: "1232" },
    c: { _id: "1233" }
  };

  const entityId = [];
  Object.keys(entity).forEach(key => {
    entityId.push(entity[key]._id);
  });
  const promise = [];
  Object.keys(entityId).forEach(async key => {
    const reviews = Review({ entityId: entityId[key] });
    promise.push(reviews);
  });
  const results = await Promise.all(promise);
};

const Review = (option) => {
  return true;
};

data();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM