在 ajax 调用承诺中的 .done() 函数之前使用回调函数



这是我想要实现的示意图:

function loadLotsofSomething() {
    for (var i=0;i<1000;i++) {
        results.push(loadOneSomething(i))
    }
    $.when.apply(this,results).done(function() {
        for (var i = 0; i < arguments.length; i++) {
            //get doSomehting(data) instead of data here
        }
    }   
}
function loadOneSomething(i) {
    return $.ajax({
        async : true,
        url: url,
        success: function(data){
            return doSomething(data);
        }
    });
}
function doSomething (x) {
    return x;
}

我希望success函数在done函数之前执行,因为在循环遍历所有调用之前修改从 ajax 调用获得的数据更简单。

就我而言,无论我在success函数中放入什么,我总是在done函数中获取原始数据。

欢迎任何帮助!

你想使用链接(就像承诺一样(。根本不要使用success;相反,请使用 then 并返回其结果:

function loadOneSomething(i) {
    return $.ajax({
        async : true,
        url: url
    }).then(function(data){
        return doSomething(data);
    });
}

这样,loadOneSomething返回的承诺是来自then的承诺,而不是来自$.ajax的承诺,其解析值是你从then返回的。

更多: $.ajax 中的 jqXHR 条目 , deferred.then .

最新更新