首页 > 解决方案 > 返回承诺而不是数据

问题描述

在我为从 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"))

标签: javascriptnode.jsaxios

解决方案


一个async函数总是返回一个承诺。要使用它,您需要await在另一个async函数中使用它。如果您不想await在另一个async功能中使用,可以将其与替代then方法一起使用。例如:

ageFinder("someUser")
.then((response) => {
  console.log(response);
}).
.catch((err) => {
  console.log(err);
});

推荐阅读