【问题标题】:Return value from an async function从异步函数返回值
【发布时间】:2022-01-14 01:30:49
【问题描述】:

如何从异步函数返回值?

我有以下承诺:

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 而不是请求返回的值。

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

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

我也试过这个:

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

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

有什么想法吗?

【问题讨论】:

  • 你试过用 var gh = ... 代替 const gh = ... 吗?
  • @TudorConstantin 是的,我仍然得到了承诺。
  • 这太疯狂了——如果你放一个 console.log(gh);在返回gh之前,显示内容
  • @Tudor Constantin 是的。我也是,但返回时不起作用。

标签: javascript async-await es6-promise


【解决方案1】:

看来你只能access that value inside of a callback

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-09-12
  • 2020-07-29
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 2021-03-04
相关资源
最近更新 更多