jquery - 使用同步ajax调用有什么缺点?

标签 jquery ajax class prototypejs

这个问题肯定适用于 jQuery,但在本例中我指的是 Prototype。在原型(prototype)文档中它说,

Since synchronous usage is rather unsettling, and usually bad taste, you should avoid changing this. Seriously.

我不确定使用同步 ajax 调用有什么缺点。似乎有很多情况您必须等待调用返回(不使用特定的回调函数)。例如,我目前使用 Prototype 的 onSuccess、onFailure 和 onComplete 来处理其余代码。

但是,我使用的 Web 服务(全部是内部的)涵盖了大多数项目,并且我的任务是创建更多可重用的代码。一个示例是返回客户属性的客户类。一个简单的示例(请记住,为了简单起见,我只展示了基本功能):

Customer = Class.create({ 

    initialize: function(customerId) { 

        new Ajax.Request('some-url', {
            method: 'get',
            parameters: {
                customerId: customerId
            },
            onSuccess: this.setCustomerInfo.bind(this)
        }

    },

    setCustomerInfo: function(response) {

        //for the sake of this example I will leave out the JSON validation

        this.customerInfo = response.responseText.evalJSON();

    } 

});

因此,使用这个简单的类,我可以在任何项目中执行以下操作来获取客户信息。

var customer = new Customer(1);

//now I have the customer info
document.write(customer.customerInfo.firstName);

使用上述代码不会打印出客户的名字。这是由于 ajax 调用是异步的。无论 Web 服务是否带回客户数据,它都会执行 document.write。但在数据返回并设置客户变量之前我不想做任何事情。为了解决这个问题,我将 ajax 调用设置为同步,这样浏览器将不会继续,直到 new Customer(1); 完成。

此方法似乎有效(将异步设置为 false),但阅读 Prototype 文档让我暂停。使用这种方法有什么缺点?有没有其他方法可以做到这一点,更有效等等?

如果有任何反馈,我将不胜感激。

最佳答案

让我们提醒您,JavaScript 是单线程的

同步 IO 调用阻塞整个线程

一个简单的解决方法是使用回调的异步风格编程。

Customer = Class.create({     
    initialize: function(customerId, cb) { 
        new Ajax.Request('some-url', {
            method: 'get',
            parameters: {
                customerId: customerId
            },
            onSuccess: (function() {
                this.setCustomerInfo.apply(this, arguments);
                cb.apply(this, arguments);
            }).bind(this)
        }
    },
    setCustomerInfo: function(response) {
        //for the sake of this example I will leave out the JSON validation
        this.customerInfo = response.responseText.evalJSON();
    }   
});

var c = new Customer(1, function() {
     document.write(customer.customerInfo.firstName);
});

关于jquery - 使用同步ajax调用有什么缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6517403/

相关文章:

c# - 如何记录 Web 服务的 JSON 请求

javascript - JAVA:删除for循环生成的div

javascript - 单击按钮时 JQuery UI 选项卡出现问题

java - 如何使 JFrame 和 JMenubar 不在 public static void main(String[] args) 中

c# - 正确使用类?

c++ - 如何在 C++ 源文件之间共享静态变量?

jQuery - 如何检查元素是数组还是单个元素

javascript - 如果我想知道用户何时从输入中删除文本,即使用户不使用键盘,我应该跟踪什么事件

javascript - 仅序列化更改的表单元素时如何处理空数组

javascript - LocalStorage 选项卡中的更改日期