Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

javascript - Dynamic AJAX promise chain with jQuery

My AJAX calls are built inside of a for loop. They need to be in order (synchronous). How do I chain them with jQuery?

var array = ['One', 'Two', 'Three'];
var arrayLength = array.length;
for (var arrayCounter = 0; arrayCounter < arrayLength; arrayCounter++) {
    var id = array[arrayCounter];
    getData(id);

    function getData(id) {
        $.ajax({
            url: 'http://example.com/' + id,
            dataType: 'jsonp',
            success: function(d) {
                var response = d;
                console.log(d);
            },
            error: function() {
                alert("ERROR");
            }
        });
    }
}   
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution using for:

var array = ['One', 'Two', 'Three'];
var id = array[0];
var data = getData(id);
for (var i = 1; i < array.length; i++) {
    // Or only the last "i" will be used
    (function (i) {
        data = data.then(function() {
            return getData(array[i]);
        });
    }(i));
}

// Also, see how better the getData can be.
function getData(id) {
    return $.ajax({
        url: 'http://example.com/' + id,
        dataType: 'jsonp',
    }).done(function(d) {
        var response = d;
        console.log(d);
    }).fail(function() {
        alert('ERROR');
    });
}

By the way, if you used a proper promises library, such as bluebird, you'd use the following code:

var array = ['One', 'Two', 'Three'];
Promise.reduce(array, function(data, id) {
    return data.promise.then(function(result) {
        return { promise: getData(id), results: data.results.push(result) };
    });
}, []).then(function(data) {
    console.log(data.results); // yay!
});

function getData(id) {
    return Promise.cast($.ajax({
        url: 'http://example.com/' + id,
        dataType: 'jsonp',
    }).done(function(d) {
        var response = d;
        console.log(d);
    }).fail(function() {
        alert('ERROR');
    }));
}

As you can see, way easier to read/write.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...