【问题标题】:Chaining jQuery promises/deferreds链接 jQuery 承诺/延迟
【发布时间】:2013-08-22 18:12:06
【问题描述】:

我有一个进程,我必须向服务器发送 ajax 请求,但需要在 ajax 请求开始之前停止调度程序,然后在请求完成后重新启动调度程序。

我使用以下代码完成了这项工作:

scheduler.stop()
         .done(function () {
                 setQuestionStatus().done(scheduler.start);
               });

不过好像应该有更简单的写法,比如:

scheduler.stop().then(setQuestionStatus).then(scheduler.start); 

我的问题是,如果这样写,setQuestionStatus 和 scheduler.start 都会在 scheduler.stop 解决后立即调用,而不是在链中的每个项目都解决后调用。

谁能告诉我在第二个例子中我做错了什么?


供您参考,scheduler.stop 和 setQuestionStatus 都使用该模式返回一个承诺:

var setQuestionStatus = function(){
  return $.Deferred(function (def) {
    // Do stuff
    def.resolve();
  }).promise();
}

【问题讨论】:

  • 你的// Do stuff是异步的吗?因为如果没有,setQuestionStatus 返回的Promise 在您调用then 之前已经实现了。
  • 好点,但是 setQuestionStatus 是异步的,所以 def.resolve() 只在 ajax.success 回调中被调用。我应该在我的示例中添加更多细节。
  • 旁注:.then(scheduler.start) 将安排调用start,但在调用中,this 不会是scheduler。你可能想要.then($.proxy(scheduler.start, scheduler) 或.then(scheduler.start.bind(scheduler))(在 ES5 系统上)。

标签: javascript jquery jquery-deferred promise


【解决方案1】:
scheduler.stop().then(setQuestionStatus).then(scheduler.start); 

我的问题是,以这种方式编写时,setQuestionStatus 和 scheduler.start 都会在 scheduler.stop 解决后立即调用,而不是在链中的每个项目都解决后调用。

这是在早期版本的 jQuery 中发现的丑陋的非standard 行为。将您的副本更新到 1.8+ 以使用 then,或者改用 pipe method。

【讨论】:

  • 天才!更新了 jQuery,现在可以按预期工作。非常感谢。
猜你喜欢
  • 2015-03-27
  • 2023-03-21
  • 1970-01-01
  • 2023-03-18
  • 2016-12-08
  • 2015-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多