【发布时间】: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