了解jQuery.在jquery上下文中延迟.AJAX(再一次)

Understanding jQuery.Deferred in the context of jQuey.AJAX (again)

本文关键字:AJAX 再一次 延迟 jQuery jquery 上下文 了解      更新时间:2023-09-26

我承认,尽管花了几个小时阅读和尝试,我还是无法从根本上理解延迟承诺和异步的一般含义。

我的目标非常非常简单:向服务器发送一些数据,并有条件地响应响应的内容。

响应将始终是一个带有saveerror键的JSON对象:

{ "save": true, "error":false} 
// or
{ "save" : false, 
  "error" : "The server has run off again; authorities have been notifed."}

我已经从jQuery API,从其他stackexchange答案,从教程等尝试了几十个和几十个变化。这些示例似乎都与本地异步活动有关。当我需要某种能力来了解AJAX请求何时完成并返回一个响应时,我可以检查并做出决定,或者知道它失败了。下面,我用评论解释了我认为正在发生的事情,这样别人就可以告诉我我失败的地方。

知道这是一个转发;作为学徒,我比一般人更不懂这一点。

var postData = {"id":7, "answerswer":"Ever since I went to Disneyland..."};
    /* when(), as I understand it, should fire an event to be 
       responded to by then() when it's contents have run their course */
var result = $.when(
       /* here I believe I'm supposed to assert what must complete 
          before the when() event has fired and before any chained 
          functions are subsequently called */
             /* this should return a jqXHR object to then(), which is,
                I'd thought, a queue of functions to call, in order, 
                UPON COMPLETION of the asynchronous bit */
             $.post("my/restful/url", postData))
    .then( function() {
        /* since "this" is the jqXHR object generated in the $.post()
           call above, and since it's supposed to be completed by now,
           it's data key should be populated by the server's response—right? */
        return this.data;
    });
    // alas, it isn't
    console.log(result.data);
    // >> undefined

大多数例子我可以找到讨论超时函数;但据我所知,这似乎是一种故障保护措施,用于任意决定何时异步部分发生故障,而不是拖延时间以完成请求的手段。实际上,如果我们所能做的只是等待,那么这与同步请求有什么不同呢?

我甚至会链接到一个新的 read-mes,教程等,如果他们以不同的方式覆盖材料,使用jQuery API中修改的例子以外的东西,或者以其他方式帮助这个流舌的白痴通过异步的标志;这是我一直在读的地方:

jQuery API: Deferred
JQuery基本原理
jQuery延迟承诺异步幸福(blog)


这是对下面@Kevin B的回应:

我试过了:

var moduleA = {
        var moduleB = {
                    postData: {"id":7, "answerswer":"Ever since I went to Disneyland..."};
                    save: function() {
                       return $.post("path/to/service", postData, null, "JSON");
                    }
        };
        var result = this.moduleB.save();
        result.done(function(resp) {
            if (resp.saved == true) {
                // never reached before completion
                console.log("yahoo");
            } else {
                console.log("Error: " + resp.error);
                // >> undefined
            }
        });

}

您的代码过于复杂了。无论你创建/使用了多少个延迟/承诺(你的示例创建了3个不同的延迟对象!)

使用done回调。

var postData = {"id":7, "answerswer":"Ever since I went to Disneyland..."};
$.post("my/restful/url", postData).done(function (result) {
    console.log(result.save, result.error);
});

您似乎对异步请求、Promise模式和javascript将函数作为参数传递的机制都有误解。

为了理解代码中真正发生的事情,我建议您使用调试器并在代码中设置一些断点。或者,也可以添加一些控制台。记录代码。通过这种方式,您可以看到程序的流程,并可能更好地理解它。另外,请确保将传递的函数参数作为then()方法的参数记录下来,以便您了解传递的内容。

好吧,你只对了一半。问题是,当您执行console.log时,承诺尚未完成,承诺的异步特性允许代码在ajax操作完成之前执行。如果你想返回一个值,你需要用。done而不是。then来处理你的promise,否则你将继续传递promise。

so that said

var result={};
  $.when(
      $.post("my/restful/url", postData))
        .done( function(data) {
        result.data=data;
  });
// here result is an object and data is a undefined since the promised has no yet been resolve.
console.log(result.data);