模拟使用递归链式的发送请求
class sendAll {
constructor(arr) {
this.arr = arr;
this.index = 0;
this.sendAll();
}
send() {
return new Promise((resolve, reject) => {
// 模拟发出请求等待返回的的过程
setTimeout(function() {
console.log(new Date());
resolve();
}, 1000);
});
}
sendAll() {
this.send().then(() => {
this.index++;
if (this.index < this.arr.length) {
this.sendAll();
}
});
}
}
let arr = [1, 2, 3, 4];
// 记得调用一下
new sendAll(arr);
也可以使用async,只需要将sendAll()函数进行替换即可,这样更加符合我们的顺序调用的相符。
async sendAll() {
for (let i = 0; i < arr.length; i++) {
await this.send();
}
}