Return value from an async function

﹥>﹥吖頭↗ 提交于 2019-12-24 00:09:20

问题


How can I return the value from an async function?

I've the following Promise:

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)
    })
  })
}

Then I use this Promise with Async/Await

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

And if I execute the function with:

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

I only get the Promise but not the value returned from the request.

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

But if I put a console.log on the gh I got the value from the request, but I don't want githubActivity() to log the value I want to return the value.

I tried this too:

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

But I still only get the Promise and not the value from the resolve.

Any thoughts?


回答1:


It looks like you can only access that value inside of a callback.

So, instead of console.log(JSON.parse(githubActivity())), use:

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


来源:https://stackoverflow.com/questions/37066266/return-value-from-an-async-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!