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

时间:2019-06-14 19:23:04

标签: javascript vue.js axios

我想根据初始API调用的响应使用axios进行API调用-异步功能是否可以?

我已经尝试过使用await / promise进行以下操作:

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 }
}

但是,这两个调用似乎都不返回任何内容。任何指针表示赞赏。

2 个答案:

答案 0 :(得分:0)

您的前两个函数返回promic,而不是实际数据。您应该尝试这样的事情:

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函数返回的对象不是promic,因此您不会用(await ).data;使代码混乱。但这是一个品味问题。

答案 1 :(得分:-2)

我认为您需要查看此链接。 https://javascript.info/async-await

在您的情况下,您可以使用.then(),但我仍然更喜欢使用async await

通过在异步函数中使用await,您可以链接一些不同的操作并使用当前操作中的最后一个调用