0

I have been trying to read up on how asynchronicity works and what promises are, but still not grasping the concept properly.

I understand that asynchronous function returns a promise but at the same time it can return content from an api in my case.

let username = list_scores[i].score.username;

      ///Await Hiscores fetches json from api.
      ///Hiscores connects to third party api and fetches data dependant on (name)

      async function getUserAsync() {
        async function getHS (name) {
          var response = await Hiscores.fetch(name).catch(console.error)
          var result = JSON.stringify(response);
          // var resultparse = JSON.parse(result)
          return result;
        }
       return getHS(username).then(result => JSON.parse(result)).catch(console.error);
      }

      let hs = getUserAsync().then(console.log)

In the above example json fetched in var response shows up in the console as intended but when I change it to try and make it return the same log as a variable

      let hs = getUserAsync().then(res => {return res;}).catch(console.error)
      console.log(hs)

It returns

Promise { <pending> }

Kind of at a loss here , been googling for few days now....

  • Possible duplicate of [Javascript (NodeJS) promise pending?](https://stackoverflow.com/questions/41411142/javascript-nodejs-promise-pending) –  Oct 29 '19 at 19:04

1 Answers1

0

so hs is an unfulfilled promise. if you were in an async function, you could await the response from getUserAsync(), but it doesnt look like you are; hence you need to handle it the old fashioned Promise way

let username = list_scores[i].score.username;
getUserAsync(username).then(user => {
    //handle user
})

///Await Hiscores fetches json from api.
///Hiscores connects to third party api and fetches data dependant on (name)

async function getHS(name) {
    var response = await Hiscores.fetch(name).catch(console.error)
    var result = JSON.stringify(response);
    // var resultparse = JSON.parse(result)
    return result;
}

async function getUserAsync(username) {
    return getHS(username).then(result => JSON.parse(result)).catch(console.error);
}
LostJon
  • 2,287
  • 11
  • 20
  • 1
    That was indeed it. I had been swapping around every line trying to find out when it stops sending pending but it was a different approach all along that I couldn't grasp. Thank you kind stranger. – CreepyMoto Oct 29 '19 at 19:28