为什么我的函数返回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];
});
由于这是一个异步函数,它将返回一个Promise. map
调用数组中每个元素的函数,获取它们返回的promise,并创建一个包含这些promise的新数组.
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屋!