【问题标题】:How can I fix this promise so I don't send back undefined我怎样才能修复这个承诺,这样我就不会发回未定义的
【发布时间】:2018-12-20 05:40:07
【问题描述】:

每次我发回时间线帖子时,我都不确定。我知道 forEach 完成的速度比承诺的执行速度要快,但我该如何解决这个问题?我尝试在 forEach 中放置一个函数并让它执行第二个承诺,但它不起作用。

  getTimelinePosts: (req, res, next) => {
    const db = req.app.get("db");

    const { userID } = req.params;
    let timelinePosts = [];

    db.getFollowing([userID]).then(friends => {
      friends.forEach((val, i, arr) => {
        db.getTimelinePosts([val.friend_id]).then(post => {
          timelinePosts.push(post);
        });
      });
      res.status(200).send(timelinePosts);
    });
  }

【问题讨论】:

  • forEach 不适用于异步代码,您最好使用常规 for:stackoverflow.com/questions/37576685/…
  • @A.Llorente A for 循环加上 await 绝对不是这里的正确工具。如果有很多friends,则需要的时间会比必要的多得多。最好使用Promise.all
  • Promise all 确实更优雅
  • 谢谢大家,不知道 Promise.all

标签: javascript reactjs express promise closures


【解决方案1】:

Map 每个getTimelinePosts 调用一个Promise,然后在Promises 的结果数组上调用Promise.all。如果你想要getTimelinePosts 到return 和Promise,那么return 也需要整个Promise 链:

return db.getFollowing([userID]).then(friends => {
  return Promise.all(friends.map(({ friend_id }) => db.getTimelinePosts(friend_id)));
})
.then(timelinePosts => {
  res.status(200).send(timelinePosts);
  // If you want `getTimelinePosts` to return a Promise that resolves with the result:
  return timelinePosts;
});

【讨论】:

    猜你喜欢
    • 2016-08-28
    • 2021-04-01
    • 1970-01-01
    • 2021-06-07
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多