【问题标题】:Async console log works but res => {return res} does not异步控制台日志有效,但 res => {return res} 无效
【发布时间】:2020-02-25 01:41:50
【问题描述】:

我一直在尝试了解异步性的工作原理以及承诺是什么,但仍然没有正确掌握这个概念。

我知道异步函数会返回一个承诺,但同时它可以从我的 api 返回内容。

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)

在上面的示例中,在 var response 中获取的 json 按预期显示在控制台中,但是当我将其更改为尝试使其返回与变量相同的日志时

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

返回

Promise { <pending> }

这里有点不知所措,现在已经在谷歌上搜索了几天......

【问题讨论】:

标签: node.js express asynchronous promise async-await


【解决方案1】:

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

【讨论】:

  • 确实如此。我一直在交换每一行,试图找出它何时停止发送待处理,但这是一种我无法掌握的不同方法。谢谢你好心的陌生人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 2019-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多