如何组织嵌套的axios调用以使其更具可读性?

Mil*_*Way 0 asynchronous vue.js axios

异步Axios调用让我有些失落。

我嵌套了Axios调用,这些调用工作得很好,但是我发现它不可读,并且我经常在这段代码中迷失了自己。

现在,我有类似的东西:


axios.get().then((response) => {
    this.pbmInfos = response.data;

    axios.get().then((response) => {
        this.contactInfos = response.data;

        axios.get().then((response) => {
            this.clientInfos = response.data).catch((error) => console.log(error));

    }).catch((error) => console.log(error));

    axios.get().then((response) => {
        this.lastViewDate = response.data).catch((error) =>  console.log(error));

}).catch((error) => console.log(error));


Run Code Online (Sandbox Code Playgroud)

(当然,为了清楚起见,我没有在get()中编写URL)

就目前而言,它看起来似乎并不太复杂,但这只是我打电话的一部分。

我试图在通用函数中将其分解,以便可以使用不同的参数来调用它,但是我没有成功,因为每个调用都需要将获取的数据分配给另一个变量,并且某些调用还需要在成功时调用另一个调用。

如果您有任何想法,我很乐意阅读。

小智 5

您可以使用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();
Run Code Online (Sandbox Code Playgroud)