在一个成功的人中进行ajax调用可以被认为是不好的做法?

Ale*_*Vaz 6 javascript ajax jquery

我们来看下面这段代码:

$.ajax({
    type: 'POST',
    dataType: dataType,
    url: 'someUrl',
    success: function(result){
        $.ajax({
            type: 'POST',
            dataType: dataType,
            url: 'anotherUrl',
            data: queryToSearch,
            success: function(anotherResult){
                (do something that uses the first one result)
            },
            error: MyObj.defaultAjaxError
        });
    },
    error: MyObj.defaultAjaxError
    });
Run Code Online (Sandbox Code Playgroud)

这可以被认为是一种不好的做法吗?它对性能有任何影响吗?如果是,是否有更好的方法来做这样的事情?

use*_*674 10

使用Promises.希望Promises/A(在jQuery 1.8+ Deferred Objects中实现),然后:

$.ajax({..}) // Promise 1
 .fail(function () {
    // Oops! This will fire if (and only if) Promise 1 failed.
 })
 .then(function () {
    // This will only fire if the first request had no error - was "done"
    // We then return a NEW promise for the 2nd request. In a proper
    // Promises/A, 'then' returns a (new) promise. (jQuery < 1.8 is broken.)
    return $.ajax({..}) // Promise 2
 })
 // Note that these are for the 2nd promise which has been returned from
 // the 'then' above OR from a 2nd promise created automatically by the default
 // failHandler.
 .fail(function () {
    // Oops! This will fire if EITHER the promises (AJAX calls) fails.
    // This happens because we are either binding to our Promise 2
    // or to the auto-rejected promise returned from the default failHandler.
 })
 .done(function () {
    // 2nd promise done - means both are done!
 })
Run Code Online (Sandbox Code Playgroud)

使用when是不合适的,因为那将是"并行"的.(实际上,when 可以与第二次调用完成后接受的"存根"承诺一起使用 - 但是这不会受到then链接的影响,并且不可能有意义地使用第二次调用的承诺直接进行串行执行. )

需要注意的一个有趣的事情是,fail和done只是为速记/受限制的形式then.这些方法可以(并且应该)用于明确意图/代码.