首页 > 解决方案 > Async console log works but res => {return res} does not

问题描述

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

标签: node.jsexpressasynchronouspromiseasync-await

解决方案


一个未兑现的诺言也是如此hs。如果你在一个async函数中,你可以await得到来自的响应getUserAsync(),但它看起来不像你;因此你需要用老式的 Promise 方式来处理它

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

推荐阅读