在for循环中有一个ajax请求,要求不把ajax请求的参数async改成false的情况下,如何实现同步效果。
其中在es6的代码在通过gulp编译的时候加入async方法会出错(原因暂时不明),所以有没有其他的方式可以实现同样的效果?
var testAjax = async function () {
for(let i = 0; i < 5; i++) {
console.log('test1: ' + i);
var url = "xxx";
await $.ajax({
url: url,
dataType: 'json',
type: "GET",
//async: false
}).then(function() {
console.log('test2: ' + i);
}).fail(function() {
console.log('error')
});
}
}
testAjax();
要求输出
test1: 0
test2: 0
test1: 1
test2: 1
test1: 2
test2: 2
.
.
.
可以使用co + generator,但是不建议这么写。
最好还是解决gulp编译的问题,实在不行,用promise重写