代码如下(借助了axios):
方法一:
let p1 = this.axios.get("role.json").then(res => {
console.log(1);
});
let p2 = this.axios.post('login').then(async res => {
await p1;
console.log(2);
});
let p3 = this.axios.get("user.json").then(async res => {
await p2;
console.log(3);
});
方法二:
async ajax() {
let p1 = axios.get("role.json")
let p2 = axios.post("login")
let p3 = axios.get("user.json")
console.log(await p1)
console.log(await p2)
console.log(await p3)
}
方法三(多个的情况):
let urls = ["role.json", "tree.json", "user.json"];
async function logInOrder(urls) {
// 并发读取远程URL
const textPromises = urls.map(async url => {
return axios.get(url); //由于是async函数,实际上是嵌套的promise对象
});
for (const textPromise of textPromises) {
console.log(await textPromise);
}
}
注意:使用map或forEach循环时程序是并发执行的,而for循环是继发执行的