【发布时间】:2017-08-13 02:06:21
【问题描述】:
我有一个排序函数,它基本上有两个 REST 步骤 - 步骤 1 和 2。 我正在通过以下方式处理它 - 调用 step1 并为其设置一个失败和一个 then 处理程序,然后进行第二次调用 - step2 具有自己的失败和处理程序。
self.step1()
.fail(self.onStep1Fail.bind(self))
.then(self.onStep1Done.bind(self))
.then(self.step2.bind(self))
.fail(self.onStep2Fail.bind(self))
.then(self.onStepDone.bind(self));
我对这个序列的解读是调用了step1,如果失败了,就会调用step1的fail方法。如果step1成功,则依次调用step1Done和step2,然后step2判断是调用step2Fail还是Step2Done。
但由于某种原因,当 step1 失败时,Step1Fail 和 Step2Fail 都会被调用 - 这是意料之外的。有谁知道为什么?另外,我怎样才能改变它以实现我想要的 - 只有在 step2 实际执行后才调用 step2Fail。
我使用以下方法实现了这一点:
var handled = false;
function onCatch(handler) {
if (!handled) {
handled = true;
handler.call(self, Array.prototype.slice.call(window.Array.apply(null, arguments), 1));
}
return $.Deferred().reject().promise();
}
self.step1()
.catch(onCatch.bind(self, self.step1Fail))
.then(self.step1Done.bind(self))
.then(self.step2.bind(self))
.catch(onCatch.bind(self, self.step2Fail))
.then(self.step2Done.bind(self));
但我正在寻找是否有更简单的方法。
【问题讨论】:
标签: javascript jquery promise jquery-deferred deferred