Why is my function returning Promise { <pending> } [duplicate]

落花浮王杯 提交于 2021-02-04 08:41:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!