首页 > 解决方案 > 我怎样才能修复这个承诺,这样我就不会发回未定义的

问题描述

每次我发回时间线帖子时,我都会不确定。我知道 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);
    });
  }

标签: javascriptreactjsexpresspromiseclosures

解决方案


Map每次getTimelinePosts调用 aPromise然后调用Promise.all结果数组Promises. 如果你也想要getTimelinePosts一个returnPromise那么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;
});

推荐阅读