2

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?

4
  • have you tried with var gh = ... instead of const gh = ... ? Commented May 6, 2016 at 7:29
  • @TudorConstantin Yeah, and still I got the Promise. Commented May 6, 2016 at 7:31
  • this is crazy - if you put a console.log(gh); before the return gh, the content is displayed Commented May 6, 2016 at 7:52
  • 1
    @Tudor Constantin Yeah. Me too, but on the return doesn't work. Commented May 6, 2016 at 7:54

1 Answer 1

3

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 ) ) )
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I see! Thank you! I was reading this too: stackoverflow.com/questions/35302431/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.