问题
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! :)
回答1:
const postCount = boards.map(async (boardI) => {
const posts = await Post.find({ board: boardI.slug });
return [boardI.slug, posts.length];
});
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.
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);
来源:https://stackoverflow.com/questions/63929347/why-is-my-function-returning-promise-pending