javascript - 返回承诺而不是数据
问题描述
在我为从 API 获取数据而编写的以下代码中,我将 promise 作为输出而不是数据。我错过了什么?有人可以帮忙吗?
const axios = require('axios');
const ageFinder = async (userName) => {
try {
let userDetails =await axios.get(`https://hacker-news.firebaseio.com/v0/user/${userName}.json`)
let user =userDetails.data
return user
} catch(err) {
console.log(err.message)
}
}
console.log(ageFinder("someUser"))
解决方案
一个async
函数总是返回一个承诺。要使用它,您需要await
在另一个async
函数中使用它。如果您不想await
在另一个async
功能中使用,可以将其与替代then
方法一起使用。例如:
ageFinder("someUser")
.then((response) => {
console.log(response);
}).
.catch((err) => {
console.log(err);
});
推荐阅读
- vb.net - 在 VB.NET 中获取两个不同列表对象的差异列表
- java - 我应该使用哪个集合(键 - 值)?
- kotlin - 有没有办法在 kotlin 中编写可暂停的委托属性?
- java - 如何指定要由 Java Sax Parser 解析的 XML 文件的一部分?
- elasticsearch - Elasticsearch:固定数据和预搜索所有字符串组合?
- javascript - Cordova Native Storage Plugin 在应用程序 iOS 中未定义
- php - 如何在没有迁移的情况下使用 Phinx?
- c++ - 带有模板参数的 Lambda 函数,而不是函数参数
- python - Python混淆矩阵中的模型精度为0%
- r - 如何为闪亮列表中的单个列表元素渲染数据表或渲染表