jQuery延迟Ajax调用和返回Ajax响应

时间:2012-11-06 11:02:32

标签: javascript ajax jquery deferred

我正在jQuery中进行同步AJAX调用。有没有办法让父函数在保持异步调用的同时返回Ajax响应。我能找到的唯一解决方案是使用回调函数。我真的不想编写一个回调函数,因为我打算在变量中使用这个对象。

例如

var ajax = serviceinterface.rawServiceCall(“http://user.myservice.com/endpoint”, “post”, {name : “xyz”});

我可能也想像这样使用它

$.when(serviceinterface.rawServiceCall(endpoint1, “get”), serviceinterface.rawSCACall(endpoint2, ‘get’)).done(function(){
    // do something here
});

这是我的功能代码,同步调用工作得非常好,但我想进行异步调用。

rawServiceCall : function(endpoint, type, payload) {
                     type = typeof type !== 'undefined' ? type : "get";
                     payload = typeof type !== 'undefined' ? payload : null;

                     return $.ajax({
                           url : endpoint,
                           type : type,
                           data : payload,
                           async : false,
                           dataType : 'json',
                           headers: {
                                 accept : "application/json"
                           },
                           success : function(data){
                                 return data;
                           }
                    });

              }

P.S - 我不想浪费CPU周期或保持网页的其他部分等待首先加载。或者更好的方法是什么?

2 个答案:

答案 0 :(得分:0)

简单的答案是否定的。行为将完全同步或完全异步。

但我不认为你有问题,因为你的代码是你寻求的解决方案的99%。您只需要知道如何评估data回调中返回的.done()

答案是.done()回调的参数与定义为ajax选项的success回调中的参数相同,即。 datatextStatusjqXHR

rawServiceCall: function(endpoint, type, payload) {
    type = type || "get";
    payload = payload || null;
    return $.ajax({
        url: endpoint,
        type: type,
        data: payload,
        async: false,
        dataType: 'json',
        headers: {
            accept: "application/json"
        }
    });
}

serviceinterface.rawServiceCall(endpoint1).done(function(data, textStatus, jqXHR) {
    //do something here
});

$.when(serviceinterface.rawServiceCall(endpoint1), serviceinterface.rawServiceCall(endpoint2)).done(function(data, textStatus, jqXHR) {
    // do something here
});

errorcomplete回调也是如此,因此jQuery.ajax承诺的回调等价物的完整列表是:

  • .done(function(data, textStatus, jqXHR){...})相当于success: function(data, textStatus, jqXHR){...}

  • .fail(function(jqXHR, textStatus, errorThrown){...})相当于error: function(jqXHR, textStatus, errorThrown){...}

  • .always(function((jqXHR, textStatus){...})相当于complete: function((jqXHR, textStatus){...}

每个jQuery promise对象都有.done().fail().always()方法,但这些方法的回调(如果有)所采用的参数因原始Deferred时传递的内容而异。 (从中得出承诺)得到解决/拒绝。

答案 1 :(得分:0)

您无法在JavaScript 中将异步方法转换为同步而不会浪费CPU周期。

停止执行代码的唯一方法是使用alert()。在JS,你永远不会睡觉,你只是闲着。