实现一个Promise.queue
可能会有如下的业务场景,我们需要一次请求多个后台接口,第二个请求在第一个请求结束后进行操作,可以抽象成以下代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
Promise.queue([
() => promise1,
() => promise2,
() => promise3
]).then();
Promise.queue([1, 2, 3].map((index) => {
return () => new Promise((resolve) => {
setTimeout(() => {
resolve(index);
}, index * 1000);
});
})).then((data) => {
// 6s 后输出
console.log(data); // [1, 2, 3];
});
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
Promise.queue = function (fns) {
if (fns.length === 0) {
Promise.resolve([])
}
const res = []
function go (index) {
const fn = fns[index]
if (fn) {
return fn().then((data) => {
res.push(data)
return go(index+1)
})
} else {
return Promise.resolve(res)
}
}
return go(0)
}
|