简体   繁体   English

如何在循环内调用异步 function?

[英]How can I call async function inside a loop?

I have below code in node.我在节点中有以下代码。 In getPosts , it reads 10 posts from database which is an async function call.getPosts中,它从数据库中读取 10 个帖子,这是一个异步 function 调用。 And for each post, it needs to read user info.并且对于每个帖子,它都需要读取用户信息。 from database which is another async function call.来自数据库,这是另一个异步 function 调用。 How can I make it work in node js?如何使它在节点 js 中工作?


const getUser = async (userId) => {
    // read user from database
}

const getPosts =async () => {
  const posts = await getPostsFromDB(10); // get 10 posts from database
  for(let i=0; i<posts.length; i++){
        posts[i].user = await getUser(posts[i].userId) // ERROR: I can't call await inside a loop
  }

}

I am thinking about using Promise.all() like below:我正在考虑使用Promise.all()如下所示:

const getPosts =async () => {
  const posts = await getPostsFromDB(10); // get 10 posts from database
  const allProms = posts.map(post => getUser(post.userId));
  Promise.all(allProms); // how can I assign each user to each post?

}

but I don't know how I can assign each user to each post after calling Promise.all() .但我不知道如何在调用Promise.all()后将每个用户分配给每个帖子。

Consider approaching the problem slightly differently.考虑稍微不同地处理问题。 If you wait for responses in an iterative loop, it'll produce poor performance.如果您在迭代循环中等待响应,则会产生较差的性能。 Instead, you could push them all into an array and wait for them — so they're all fetching at the same time.相反,您可以将它们全部推入一个数组并等待它们——这样它们就可以同时获取。

const getUser = async (userId) => {
  try {
    // read
  } catch (e) {
    // catch errors
  }

  // return data
}

const getPosts = async () => {
  const posts = await getPostsFromDB(10); // get 10 posts from database
  const userRequests = posts.map((post, index) => getUser(post.userId))
  const users = await Promise.all(userRequests)

  return posts.map((post, index) => {
    post.user = users[index]
  })
}

If you think you may have duplicate userId s, consider forming a list of users you can reference before calling getUser .如果您认为您可能有重复的userId ,请考虑在调用getUser之前形成您可以引用的用户列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM