异步AJAX调用返回什么?

Bob*_*nes 2 ajax notify promise deferred

我正在尝试创建一个测试用例来监视多个并行异步服务器任务的进度.我的代码有点工作,但有几件我不明白.首先,下面的$ .ajax调用返回什么?从理论上讲,它应该返回undefined,但似乎并非如此.

function doParallel() {    
    var promiseA, promiseB, handleSuccess, handleFailure;
    var dataA = JSON.stringify({ size: a });
    var dataB = JSON.stringify({ size: b });

    promiseA = $.ajax({
        url: testGlobal.urlA, 
        data: dataA,
        type: "POST",
        async: true,
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        success: function (rtnData) {
            //  Get the result
            result = (rtnData === undefined) ? null : $.parseJSON(rtnData.d);
        },
        error: function (xhr, textStatus, errorThrown) {
            //  Whoops! didn't work
            reportAjaxError(xhr, textStatus, url, data);
        },
        complete: function (xhr, textStatus) {
            //  Errors have already been handled, so only 
            //  deal with success cases
        }
    });  <--- WHAT GETS RETURNED TO PROMISE HERE?

... (same code for promiseB, etc.
    var notifyingPromiseA = intervalPromise(2000, 'a');
    var notifyingPromiseB = intervalPromise(2000, 'b');

...
    promiseA.done(function() {
        log("A done");
    }
    promiseB.done(function() {
        log("B done");
    }
    $.when(promiseA, promiseB).done(function() { log ("All done") });
}

function intervalPromise(millis, source) {
    var deferred = $.Deferred();
    //checkProgress();
    log("Checking progress on " + source);
    var id = setInterval(function () {
        deferred.notify();
        if (testGlobal.aDone && testGlobal.bDone) {
            clearInterval(id);
            deferred.resolve();
        }
    }, millis);
    return deferred.promise();
}
Run Code Online (Sandbox Code Playgroud)

...

and*_*eer 6

$.ajax()返回XMLHttpRequest对象.从jQuery v1.5开始,$.ajax()还实现并返回一个Promise/ Deferredinterface.

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/category/deferred-object/

使用a Promise,您可以根据原始ajax调用的结果链接其他回调.

// setup interval / timer to update UI not finished / still working logic

$.ajax().done(function() {
    // clear UI not fninshed / still working logic
});
Run Code Online (Sandbox Code Playgroud)