Return 来自异步函数的值

Return value from an async function

如何 return 来自异步函数的值?

我有以下承诺:

function reqGitActivity (url) {
  const options = {
    url: url,
    headers: {
      'User-Agent': 'request'
    }
  }

  return new Promise((resolve, reject) => {
    request(options, (err, res, body) => {
      if (err) {
        reject(err)
        return
      }
      resolve(body)
    })
  })
}

然后我将这个 Promise 与 Async/Await

一起使用
async function githubActivity () {
    const gh = await reqGitActivity(`https://api.github.com/users/${github}/events`)
    return gh
}

如果我执行函数:

console.log(JSON.parse(githubActivity()))

我只得到 Promise,但没有从请求中 return 得到值。

Promise {
     _c: [],
     _a: undefined,
     _s: 0,
     _d: false,
     _v: undefined,
     _h: 0,
     _n: false }

但是如果我在 gh 上放置一个 console.log 我从请求中得到了值,但我不想 githubActivity() 记录我想要的值 return值。

我也试过这个:

async function githubActivity () {
    return await reqGitActivity(`https://api.github.com/users/${github}/events`)
    .then(function (res) {
      return res
    })
}

但我仍然只得到 Promise 而不是 resolve 的价值。

有什么想法吗?

看来你只能

因此,不要使用 console.log(JSON.parse(githubActivity())),而是使用:

githubActivity().then( body => console.log( JSON.parse( body ) ) )