方式一、递归
let arr = [];
(function loop(index) {
if (index >= 0) {//递归终止条件
//模仿ajax请求
setTimeout(() => { //一次回调完成才进行下一次回调
arr.push(index * 1000);
loop(--index);
}, index * 1000);
} else {
console.log('递归方式结果:',arr);
}
})(3);
测试结果:
方式二、Promise
function p(time) {
return new Promise((resolve, reject) => {
//模仿ajax请求
setTimeout(() => {
resolve(time);
}, time);
});
}
(async function foo() {
let arr = [];
for (let i = 3000; i >= 0; i -= 1000) {
arr.push(await p(i)); //await会阻塞当前异步函数的执行,等待promise返回处理结果
}
console.log('Promise方式结果:',arr);
})();
测试结果:
方式三、Ajax的async属性
let arr = [];
for (let i = 0; i < 3; i++) {
$.ajax({
url: 'http://poetry.apiopen.top/getTime',
type: 'get',
async: false, //默认为true,ajax默认异步执行,通过async: false变为同步方式执行即可
success(resp) {
if (resp && resp.result) {
arr.push(i+" "+resp.result.dateTime);
}
}
});
}
console.log("async方式结果:", arr);
测试结果:
更多推荐
【JavaScript】多种方式解决在for循环中调用ajax,并等待返回结果后才进行下一次循环
发布评论