jquery – 将多个done()回调链接到相同的延迟promise

简而言之,我希望有一个通用回调,在成功的ajax调用的情况下始终触发,然后根据调用方法的位置单独的回调功能.

这似乎有效.我的问题是,如果这是对promise对象的正确使用,并且如果可以安全地假设同一类型的多个promise回调总是按顺序堆栈?

var dfd = $.Deferred(),promise = dfd.promise();

promise.done(function(){
    console.log(1);
}).done(function(){
    console.log(2);
});

dfd.resolve();

http://jsfiddle.net/4ax4nxbh/

解决方法

这是jQuery中延迟对象的正确和记录使用.文档 clearly states

Callbacks are executed in the order they were added.

它在其他承诺库中的工作方式不同,并且通常.然后,无论如何都优先使用.(在后面的答案中解释).但是如果你使用jQuery promises,如果它们是同步的,它将按顺序堆栈.

所以直接回答你的问题是肯定的.

但是,您也可以使用异步代码执行此操作,并使用.then更好地链接

promise.then(function(){
    console.log(1);
}).then(function(){
    console.log(2);
}).then(function(){
    return $.get(...);
}).then(function(){
    console.log(3); // this always executes after the $.get finishes.
});

基本上,done添加一个处理程序并返回相同的promise.然后返回一个从最后一个链接的新promise.一般来说,我只使用.done来终止链,如果你想保留返回值(函数()的参数{)

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...