为什么我的函数返回 Promise { <pending> }

har*_*ung -3 javascript mongoose node.js promise

作为我的第一个真正的 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');
  }
};
Run Code Online (Sandbox Code Playgroud)

这是控制台日志的结果:

[0] [
[0]   Promise { <pending> },
[0]   Promise { <pending> },
[0]   Promise { <pending> },
[0]   Promise { <pending> },
[0]   Promise { <pending> }
[0] ]
Run Code Online (Sandbox Code Playgroud)

Nic*_*wer 6

const postCount = boards.map(async (boardI) => {
  const posts = await Post.find({ board: boardI.slug });
  return [boardI.slug, posts.length];
});
Run Code Online (Sandbox Code Playgroud)

由于这是一个异步函数,因此它将返回一个承诺。map为数组的每个元素调用函数,获取它们返回的 Promise,并创建一个包含这些 Promise 的新数组。

如果您想等待 Promise 数组每次完成,请使用 Promise.all 将它们组合成一个 Promise,然后等待结果。

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);
Run Code Online (Sandbox Code Playgroud)