异步请求之并发处理

如何解决处理多个数据接口的并发请求。 当我们首页需要同时请求多个接口时,如何做到全部请求完成后,再做处理, 根据各个接口的数据渲染页面。

在 Jquery 1.5 中新增了when函数,可以执行一个或多个异步事件

1
2
3
4
5
6
7
8
9
10
11
$.when(
$.getJSON('https://easydoc.xyz/a'),
$.getJSON('https://easydoc.xyz/b'),
$.getJSON('https://easydoc.xyz/c')
)
.done((a, b, c) => {
console.log(a, b, c);
})
.fail(e => {
console.log(e);
});

同样使用 axios.all 也可以实现同时处理多个请求

1
2
3
4
5
6
7
8
9
10
11
axios
.all([
axios.get('https://easydoc.xyz/a'),
axios.get('https://easydoc.xyz/b'),
axios.get('https://easydoc.xyz/c'),
])
.then(
axios.spread((a, b, c) => {
console.log(a, b, c);
})
);

axios 实际上是使用了 Promise 所以也可以使用 Promise.all来实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Promise.all([
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 5e3);
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 3e3);
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3);
}, 6e3);
}),
]).then(result => {
console.log(result);
});

当然也可以使用 for 来实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const req = [
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 5e3);
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 3e3);
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3);
}, 6e3);
}),
];
(async () => {
for (let index = 0; index < req.length; index++) {
console.log(await req[index]);
}
})();

当然,你也可以什么都不用利用 Promise 的特性也可以实现

这里利用了 Promise 一旦创建就立即执行的特点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const [a, b, c] = [
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 5e3);
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 3e3);
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(3);
}, 6e3);
}),
];
(async () => {
const result1 = await a;
const result2 = await b;
const result3 = await c;
console.log(result1, result2, result3);
})();
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%