node.js - 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....
解决方案
一个未兑现的诺言也是如此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);
}
推荐阅读
- reactjs - ReactJS:组件未在嵌套路由中呈现
- javascript - 我用 JavaScript 创建了一个日期计算器,但即使 setInterval() 也无法更新数字
- ruby-on-rails - Rails + PostgreSQL:如果一列中的值为NULL,则按另一列中的值搜索
- wpf - 锣拖拽:拖拽效果边框不适合元素
- c++ - 视图对象的 const 返回类型
- linux - 物理服务器 Centos“开始更新 UTMP 关于系统启动/关闭”
- android - ListAdapter Diff 不会在同一个列表实例上分派更新,但也不会在与 LiveData 不同的列表上分派更新
- c# - 如何使用 StackPanel 动态调整 ScrollViewer 的大小?
- python - 无输出/密码打印 - zip 破解程序 进程以退出代码 0 完成
- javascript - Vuejs - 为什么一个方法的触发也会通过v-if触发一个不相关的方法