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

我们来看下面这段代码:

$.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 }); 

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

使用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! }) 

使用when是不合适的,因为那将是“并行”的。 (实际上, when第二次调用完成when 可以使用有线接收的“存根”承诺 - 但是这不会从then链接中受益,并且不可能有意义地使用第二次调用的承诺直接进行串行执行。)

需要注意的一件有趣的事情是, faildone只是then /限制forms的缩写 。 这些方法可以(并且应该)用于明确意图/代码。

如果需要回调按顺序运行,则需要以这种方式执行。 如果他们需要并行完成(订单无法保证),那么你不应该这样做。 这不是好事或坏事。 这是你需要完成的事情。

这样做没有明显的错误,但你可以考虑使用jQuery Deferred Objects。