【问题标题】:Return the promise from sequential jQuery ajax calls?从连续的 jQuery ajax 调用中返回承诺?
【发布时间】:2013-10-01 16:41:27
【问题描述】:

此函数进行两次连续的 AJAX 调用,page1 返回的数据用于对 page2 的请求。

function call() {
    return $.ajax("http://example.com/page1").done(function(d) { 
        $.ajax("http://example.com/page2", { data: d.foo });
    });
}

我希望 call() 返回一个仅在 page2 完成加载后才解析的承诺,而不是在 page1 像现在这样完成时,所以可以这样做:

call().done(function() { console.log("page2 has loaded.") });

最好的方法是什么?

【问题讨论】:

标签: javascript jquery promise


【解决方案1】:

call() 只需要非常轻微的修改。

done 更改为then 并返回内部$.ajax()

function call() {
    return $.ajax("http://example.com/page1").then(function(d) {
        return $.ajax("http://example.com/page2", { data: d.foo });
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2014-05-07
    • 2014-06-14
    • 2018-07-30
    相关资源
    最近更新 更多