javascript - 我怎样才能修复这个承诺,这样我就不会发回未定义的
问题描述
每次我发回时间线帖子时,我都会不确定。我知道 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);
});
}
解决方案
Map
每次getTimelinePosts
调用 aPromise
然后调用Promise.all
结果数组Promises
. 如果你也想要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;
});
推荐阅读
- javascript - 使用 For 循环绘制矩形
- c++ - 我在测试传递参数作为左值复制、右值移动和通过引用传递时观察到的行为问题
- jmeter - Badboy 软件中显示空白浏览器页面。任何人都可以帮我解决这个问题吗?
- javascript - Python Django - 如何在不使用 Ajax 刷新的情况下在页面上显示模型更改?
- javascript - redux-form 从另一个下拉列表更改下拉选项列表
- scala - 处理隐式类型类冲突
- python - Python:根据另一列名称获取一列的值
- node.js - 无法使用 node-dev 监视目录
- mongodb - MongoDB 数据模型 - 一个文档可以链接到具有不同状态的多个文档
- python - 使用 pandas 模式的 Python 库列验证