为什么我的函数返回 Promise { <pending>} [英] Why is my function returning Promise { <pending> }
问题描述
作为我的第一个真正的 MERN 项目,我正在构建一个留言板.我目前正在使用节点路由来请求板名称及其相关的帖子数,但我遇到了一个问题.我没有得到我需要的值,而是收到信息告诉我有一个未决的承诺,这在我使用 async/await 时看起来很奇怪.这是函数:
As my first real MERN project, I'm building a message board. I'm currently working on a node route to request the board names with their associated post count but I've hit an issue. Instead of getting the values that I need, I'm recieving info telling me there is a promise pending, which seems odd as I'm using async/await. Here's the function:
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');
}
};
这是控制台日志的结果:
and here is the result of the console log:
[0] [
[0] Promise { <pending> },
[0] Promise { <pending> },
[0] Promise { <pending> },
[0] Promise { <pending> },
[0] Promise { <pending> }
[0] ]
在此先感谢所有/任何帮助!:)
Thanks in advance for all/any help with this! :)
推荐答案
const postCount = boards.map(async (boardI) => {
const posts = await Post.find({ board: boardI.slug });
return [boardI.slug, posts.length];
});
由于这是一个异步函数,它将返回一个承诺.map
为数组的每个元素调用该函数,获取它们返回的承诺,并创建一个包含这些承诺的新数组.
Since this is an async function, it will return a promise. map
calls the function for each element of the array, gets the promises they return, and creates a new array containing those promises.
如果您想等待每个完成的承诺数组,请使用 Promise.all 将它们组合成一个单一的承诺,然后等待结果.
If you would like to wait for that array of promises to each finish, use Promise.all to combine them into a single promise, and then await the result.
const promises = boards.map(async (boardI) => {
const posts = await Post.find({ board: boardI.slug });
return [boardI.slug, posts.length];
});
const postCount = await Promise.all(promises);
console.log(postCount);
这篇关于为什么我的函数返回 Promise { <pending>}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!