简体   繁体   English

链接的jQuery deferred.then()未返回正确的承诺

[英]Chained jquery deferred.then() not returning the proper promise

I've taken the sample code from the jquery deferred.then() documentation: Chain tasks. 我已经从jquery deferred.then()文档中获取了示例代码: 链任务。

The problem I found is with the chained.done handler that, from what I understand, should be called when all the requests are done. 我发现的问题chained.done处理程序,据我了解,所有请求完成后应调用该处理程序。 Instead the handler is executed when the first request is done, and it retrieves the payload from this same request. 取而代之的是,处理程序在第一个请求完成时执行,并从同一请求中检索有效负载。

This is the code that I'm using: 这是我正在使用的代码:

var request = $.ajax("http://www.json-generator.com/j/bPyGnSXXTm", {
    dataType: "json",
    crossDomain: true
}),
    chained = request.then(function (data) {
        console.log('First call, data:', data);
        $('body').append('<p>' + 'First call, data: ' + JSON.stringify(data) + '</p>');
        return $.ajax(data[0].url, {
            crossDomain: true
        });
    });

chained.done(function (data) {
    // data retrieved from url2 as provided by the first request
    console.log('Second call, data:', data);
    $('body').append('<p>' + 'Second call, data: ' + JSON.stringify(data) + '</p>');
});

You can find a jsfiddle here . 您可以在此处找到jsfiddle

Furthermore you can open console and see that the handler is being executed before the second request, (Activate log XMLHttpRequests). 此外,您可以打开控制台,并在第二个请求(激活日志XMLHttpRequests)之前看到处理程序正在执行。

From my understanding the chained is getting the value of request , and not the returned value of the $.ajax as it should. 根据我的理解, chained获取的是request的值,而不是$.ajax的返回值。

Using jQuery prior to 1.8, you need to use .pipe() instead of then() : 使用1.8之前的jQuery,您需要使用.pipe()而不是then()

chained = request.pipe(function (data) {...});

See DOC for change between version: http://api.jquery.com/deferred.then 有关版本之间的更改,请参见DOC: http : //api.jquery.com/deferred.then

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM