【问题标题】:Chained jQuery promises execute early链接的 jQuery 承诺提前执行
【发布时间】:2014-12-01 23:56:37
【问题描述】:

我正在为 jQuery 的承诺和动画而苦苦挣扎。这是一个简化的案例:

var title = $('#intro h2');
title.fadeOut(2000).promise()
    .then(function () { title.fadeIn(4000); } )
    .then(function () { title.css( {'background-color':'red'} ); } );

我希望标题 ($('#intro h2')) 淡出,然后淡入,然后其背景颜色变为红色。相反,在标题淡入之前,背景会变为红色

发生了什么事?

我如何使用 Promise 来确保正确的事件顺序?

【问题讨论】:

  • 看起来您应该使用 jQuery 的 queue 而不是 promise

标签: javascript jquery animation promise


【解决方案1】:

你的then 回调没有返回一个promise,所以promise 链不知道要等待什么。它不会等待undefined。使用

title.fadeOut(2000).promise().then(function(){
    return title.fadeIn(4000).promise();
//  ^^^^^^                   ^^^^^^^^^^
}).then(function() {
    title.css({'background-color':'red'})
})

请注意,这个动画也可以单独使用动画队列来完成:

title.fadeOut(2000).fadeIn(4000, function(){title.css('background-color','red')})

【讨论】:

  • 感谢您的回答。
  • 我确实知道链接$foo.fadeOut(t).fadeIn(t2);,但我的实际用例更复杂,这个例子是我能想到的最简单的例子来展示我的经历。实际用例涉及创建辅助函数以跨多个动画效果标准化动画行为(定时、缓动、返回承诺)。问题的出现没有辅助函数的复杂性,所以我只给出了这个简化的例子。
【解决方案2】:

您需要从您的第一个then() 回调中返回淡入动画的承诺。

否则,promise 链没有任何等待,所以它立即执行。

title.fadeOut(2000).promise()
    .then(function () { return title.fadeIn(4000).promise(); })
    .then(function () { title.css( {'background-color':'red'} ); });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多