【发布时间】:2021-01-03 20:01:18
【问题描述】:
作为我的第一个真正的 MERN 项目,我正在构建一个留言板。我目前正在研究一个节点路由,以请求具有相关帖子计数的板名称,但我遇到了一个问题。我收到的信息不是我需要的值,而是告诉我有一个未决的承诺,这看起来很奇怪,因为我正在使用 async/await。函数如下:
exports.postsPerBoard = async (req, res) => {
try {
const boards = await Board.find();
const postCount = boards.map(async (boardI) => {
const posts = await Post.find({ board: boardI.slug });
return [boardI.slug, posts.length];
});
console.log(postCount);
res.send(postCount);
} catch (err) {
console.error(err.message);
res.status(500).send('server error');
}
};
这是控制台日志的结果:
[0] [
[0] Promise { <pending> },
[0] Promise { <pending> },
[0] Promise { <pending> },
[0] Promise { <pending> },
[0] Promise { <pending> }
[0] ]
在此先感谢您提供的所有/任何帮助! :)
【问题讨论】:
-
当你调用一个没有
await的异步函数时,它会返回一个promise。 -
使用
Promise.all()解决所有的promise。 -
我不认为我已经这样做了,但是......我有吗?
-
boards.map(async ...)正在调用异步函数而不使用await。 -
@Barmar - board.map 不是异步的 - 它返回相同的数组,带或不带
await
标签: javascript node.js mongoose promise