【发布时间】: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