2
votes

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
have you tried with var gh = ... instead of const gh = ... ?Tudor Constantin
@TudorConstantin Yeah, and still I got the Promise.Rog
this is crazy - if you put a console.log(gh); before the return gh, the content is displayedTudor Constantin
@Tudor Constantin Yeah. Me too, but on the return doesn't work.Rog

1 Answers

3
votes

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