【问题标题】:Chained jquery deferred.then() not returning the proper promise链接的 jquery deferred.then() 没有返回正确的承诺
【发布时间】:2014-02-14 11:00:30
【问题描述】:

我从 jquery deferred.then() 文档中获取了示例代码:Chain tasks.

问题我发现是 chained.done 处理程序,据我了解,应该在所有请求完成后调用它。 相反处理程序在第一个请求完成时执行,并从同一请求中检索有效负载。

这是我正在使用的代码:

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>');
});

您可以找到jsfiddle here

此外,您可以打开控制台并查看处理程序在第二个请求之前执行,(激活日志 XMLHttpRequests)。

据我了解,chained 正在获取request 的值,而不是应有的$.ajax 的返回值。

【问题讨论】:

  • 在你的代码中,chained 仍然是第一个调用
  • @A.Wolff 我的代码复制了 jquey 文档中的那个,变量 chained 被分配给 request.then 函数,也许我不明白你的评论......你能否详细说明再来一点?谢谢!
  • 好吧,我明白了,then 在 jQuery 1.8.x(?) AFAIK 之前有问题,看,你需要将 jQuery 升级到 1.8 或使用 pipe() 而不是 then() 管道:@987654323 @ 或 jQuery 1.8 jsfiddle.net/nGthY/3
  • @A.Wolff 你完全正确,它与 jquery 1.8.3 一样工作!
  • 我被锁定在 1.7,所以您提供的 pipe 解决方案效果最好。 @A.Wolff 你介意从你的评论中回答吗?

标签: javascript jquery promise jquery-deferred chaining


【解决方案1】:

使用1.8之前的jQuery,需要使用.pipe()而不是then()

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

有关版本之间的更改,请参阅文档:http://api.jquery.com/deferred.then

【讨论】:

    猜你喜欢
    • 2023-01-27
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 2018-12-30
    • 1970-01-01
    相关资源
    最近更新 更多