一、连续调用
假设有一个参数数组data = [1, 2, 3, 4],每项都需要组织成一个请求发送,每项发送完之后发送下一项(无论发送成功或失败):
先组织一个发送数据的函数postData
const postData = item => {
return new Promise((resolve) => {
setTimeout(() => {
if (Math.random() > 0.5) {
console.log(item, '发送成功');
} else {
console.log(item, '发送失败');
}
resolve();
}, 1000);
});
};
1. 使用reduce拼接
data.reduce((c, n) => {
return c.then(() => postData(n));
}, Promise.resolve());
2. 使用回调 和 递归
function startPostData(index) {
postData(data[index]).then(() => {
if (index === data.length - 1) {
return;
}
startPostData(index + 1);
});
}
startPostData(0);
3. 使用async/await 和 递归
async function postDataByLoop() {
for (let item of data) {
await postData(item);
}
}
postDataByLoop();
二、分批调用
假设有一个参数数组data = [1, 2, 3, 4, 5, 6, 7],每批3项,组织成一个请求发送,例如7项就发送3次,每次结束后再开始发送下一批:










网友评论