繁体   English   中英

如何在异步函数中返回值之前等待 Promise.all 解决(表达 JS)

[英]How to wait for Promise.all to resolve before returning values in async function (express JS)

我对 JS 非常陌生,尤其是异步编程。 我正在尝试构建一个显示 gitHub 用户信息的 Express+React 应用程序(包括一些带有 5 次提交的存储库)。

要执行后者,我使用 Promise.all 和 map 来获取数组中每个 repo 的提交,并返回一个包含添加到每个 repo 的提交的数组。

当我在 map 函数中 console.log 新的 repo 时,它可以工作,但是当我尝试返回数组时,对象是未定义的。

我认为这是因为在 Promise 解决之前返回正在执行。 谁能帮我解决这个问题?

//takes a username and collection of repos and finds their commits using fetch to github API. Returns the array of repos with their commits as a new property
const getGitHubCommits = async (username, repos) => {
  try {
    const repositories = await Promise.all(
      repos.map(async (repo) => {
        fetch(`https://api.github.com/repos/${username}/${repo.name}/commits?per_page=5`).then(response => response.json())
          .then(async response => {
            repo.commits = response.slice(0, 5)
            console.log(repo)
            return await repo
          })
      })
    );

    console.log(repositories)
    return repositories
  } catch (error) {
    console.log(error)
    return "No commits found found"
  }
}

您根本不需要async / await 只要将async放在函数前面,该函数就会返回一个 Promise,然后您需要解决该 Promise。

这是一个更好的版本:

const getGitHubCommits = (username, repos) => {
  return Promise.all(
    repos.map((repo) =>
      fetch(
        `https://api.github.com/repos/${username}/${repo.name}/commits?per_page=5`
      )
        .then((response) => response.json())
        .then((response) => {
          repo.commits = response.slice(0, 5)
          return repo
        })
    )
  )
}

这干净多了。 稍后您需要解决承诺:

getGitHubCommits('...', ['...'])
  .then((result) => {
    console.log(result)
  })
  .catch((err) => {
    console.log(err)
  })

或者,如果您在异步函数中调用它,您可以在此处使用async / await

try {
  let commits = await getGitHubCommits('..', ['..'])
  console.log(commits)
} catch (err) {
  console.log(err)
}

暂无
暂无

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

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