[Vuejs]-How to organize nested axios calls to make them more readable?

5👍

You can use async/await

async function fetchData() {
  let res1 = await axios.get("https://reqres.in/1");
  let res2 = await axios.get("https://reqres.in/2");
  let res3 = await axios.get("https://reqres.in/3");
}
await fetchData();

2👍

As @protestator said, you can use async/await but you can also use promises, but in this way:

axios.get("https://reqres.in/1").then((response) => {
    return response.data;
}).then((response) => {
    return axios.get("https://reqres.in/2")
}).then((response) => {
    return axios.get("https://reqres.in/3")
}).then((response) => {
    this.lastViewDate = response.data
}).catch((error) => console.log(error));

In case of any doubt with Promises, this is my Bible:
https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

Bonus: more concise way:

axios.get("https://reqres.in/1")
        .then(response => response.data)
        .then(response => axios.get("https://reqres.in/2"))
        .then(response => axios.get("https://reqres.in/3"))
        .then(response => this.lastViewDate = response.data)
        .catch((error) => console.log(error));

Leave a comment