Javascript 使用axios链接异步调用的理想方法

Javascript 使用axios链接异步调用的理想方法,javascript,vue.js,axios,Javascript,Vue.js,Axios,我想根据初始API调用的响应使用axios进行API调用-异步函数是否可以这样做 我尝试了以下几点,等待/承诺: function get_user(value){ return axios.get( "https://apicall/" + value ) } function get_user_posts(username){ return axios.get("https://apicall/" + username) } var UsersOutput = async fun

我想根据初始API调用的响应使用axios进行API调用-异步函数是否可以这样做

我尝试了以下几点,等待/承诺:

function get_user(value){
  return axios.get( "https://apicall/" + value )
}

function get_user_posts(username){
  return axios.get("https://apicall/" + username)
}

var UsersOutput = async function () {
  const userProfile = await get_user(2928928);
  const userPosts = await get_user_posts(userProfile.data.username);
  return { userProfile, userPosts }
}

但这两个调用似乎都没有返回任何结果。感谢您的指点。

我想您需要查看此链接。

在您的例子中,您可以使用.then(),但我仍然更喜欢使用async wait


通过在异步函数中使用wait,您可以链接一些不同的操作,并使用当前函数中的最后一个调用。前两个函数返回的是承诺,而不是实际数据。您应该尝试以下方法:

async function get_user(value){
  return (await axios.get( "https://apicall/" + value )).data;
}

async function get_user_posts(username){
  return (await axios.get("https://apicall/" + username)).data;
}
或者,如果前两个函数保持不变:

var UsersOutput = async function () {
  const userProfile = (await get_user(2928928)).data;
  const userPosts = (await get_user_posts(userProfile.data.username)).data;
  return { userProfile, userPosts }
}

一、 就个人而言,更好地找到第一个选项,因为getter函数返回的是对象而不是promices,所以代码中不会出现
(wait).data。但这是品味的问题。

是的,这是可能的,这就是异步/等待的要点。这个问题无法回答。“什么都没有”是什么意思<代码>未定义
<代码>空值?你是唯一可以调试调用并找出错误的人。不知道如何使用UsersOutput。请提供一种复制问题的方法。如果静态JSON文件可以做到这一点,那么请提供一个使用它们的可行演示。这是目前最理想的方式。str的问题是
UsersOutput
将返回一个Promise对象。因此,对该函数的调用应该如下所示:
UsersOutput()。然后(…)
。如果不是,那可能是一个问题。否则,正如Estus指出的,这可能是一个AJAX问题。我们没有足够的信息。“但这似乎没有返回任何信息”-您如何确定这一点?在示例代码中,您甚至不调用
UsersOutput
,更不用说检查它返回的内容了。在JavaScript中,以大写字母开头的变量名传统上用于构造函数,因为您没有编写构造函数,所以应该调用它
UsersOutput