es6中 for循环中ajax请求问题

在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
.
.
.
阅读 3.6k
4 个回答

可以使用co + generator,但是不建议这么写。

最好还是解决gulp编译的问题,实在不行,用promise重写

var testAjax = async function () {
    var promise = Promise.resolve()
    for(let i = 0; i < 5; i++) {
        promise = promise.then(function(){
            console.log('test1: ' + i);
            let url = "xxx";
            return $.ajax({
                url: url,
                dataType: 'json',
                type: "GET",
                //async: false
            }).then(function() {
                console.log('test2: ' + i);
            })
        })
    }
}
testAjax();

使用 async...await 可以满足你的需求的,换个请求的写法即可:

const testAjax = async function () {
    const url = 'xxx';
    for(let i = 0; i < 5; i++) {
        console.log('test1: ' + i);
        let result
        try {
            result = await $.ajax({
                url: url,
                dataType: 'json',
                type: 'GET',
            });
        } catch (error) {
            console.log('error', error);
        }
        console.log('test2: ' + i, result);
    }
}
testAjax();
var testAjax = function () {
    for(let i = 0; i < 5; i++) {
    // 用闭包保存i值
        (function (i) {
            console.log('test1: ' + i);
            var url = "xxx";
              $.ajax({
                url: url,
                dataType: 'json',
                type: "GET",
                //async: false
            }).then(function() {
                console.log('test2: ' + i);
            }).fail(function() {
                console.log('error')
            });
        })(i)
    }
}
testAjax();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题