使得内部一次成功的Ajax调用可以被认为是不好的做法? [英] Making an ajax call inside a successful one can be considered bad practice?

查看:107
本文介绍了使得内部一次成功的Ajax调用可以被认为是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看下面这段code:

Let's take the following piece of code:

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

这可以被认为是不好的做法?它是否会对性能产生任何冲击吗?如果是的话,有没有更好的办法做这样的事情?

Can this be considered a bad practice? Does it have any hit on performance? If yes, is there a better way to do something like this?

推荐答案

使用的承诺。我们希望,承诺/ A (作为的 jQuery中实施的 1.8 + 的延期对象),则:

Use Promises. Hopefully, Promises/A (as implemented in jQuery 1.8+ Deferred Objects), then:

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

使用是不恰当的,因为那将是平行。 (实际上,可以的使用与接线第二个呼叫完成时接受一个存根的承诺 - 不过,这并不受益于然后链接,它是没有意义的使用的承诺,从第二个呼叫直接用于串行执行。)

Using when is not appropriate, because that would be "in parallel". (Actually, when could be used with a "stub" promise that is wired to be accepted when the 2nd call completes - however this doesn't benefit from then chaining and it's not possible to meaningfully use the promise from the 2nd call directly for serial execution.)

一个有趣的事情要注意的是 失败完成只是速记的/受限制的形式然后 的。这些方法可以(也应该)被用于清晰的意图/ code。

One interesting thing to note is that fail and done are just shorthands for/restricted forms of then. These methods can (and should) be used for clarity of intent/code.

这篇关于使得内部一次成功的Ajax调用可以被认为是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆