jquery – 链接$.Deferred

我希望理解为什么我在尝试直接链接延迟对象时会遇到不同的行为,而不是尝试通过将对象保存在变量中并在该变量上调用一个或多个延迟方法来进行链接.

将对象保存在变量中时,发送到每个函数的值是相同的(在下面的代码片段的情况下,5) – 即在这种情况下值不会过滤.当直接链接时,值会过滤…所以我不清楚在几个不同的语句中设置Deferred.pipe()时如何进行过滤.通过我对jquery docs的阅读,它应该是可能的:

The Deferred object is chainable, similar to the way a jQuery object is chainable, but it has its own methods. After creating a Deferred object, you can use any of the methods below by either chaining directly from the object creation or saving the object in a variable and invoking one or more methods on that variable.

我究竟做错了什么?

这是我的代码:

<script type="text/javascript">
$(document).ready(function () {
// This works as expected - alert(20)

var defer = new $.Deferred();
defer.pipe(myFunction).pipe(myFunction).pipe(myAlert);
defer.resolve(5);

// This does not work as expected - alert(5)
var defer2 = new $.Deferred();
defer2.pipe(myFunction);
defer2.pipe(myFunction);
defer2.pipe(myAlert);
defer2.resolve(5);

});

var myFunction = function (value) {
return value * 2;
}

var myAlert = function (value) {
alert('The value is ' + value);
}
</script>

最佳答案 $.Deferred对象确实是可链接的,但是在你的第二个场景中,你没有链接任何东西;当$.Deferred被解析或拒绝时,您只是将多个管道分配给要独立执行的$.Deferred对象.换句话说,您忽略了返回的Promise对象,该对象包含要传递给链中下一个.pipe()的过滤/修改值.

docs

The deferred.pipe() method returns a new promise that filters the
status and values of a deferred through a function.

要在第二个示例中实现所需,请管理生成的Promise而不是原始的$.Deferred对象:

var defer2 = new $.Deferred();
var promise = defer2.pipe(myFunction);
promise = promise.pipe(myFunction); // pipe and update promise
promise.pipe(myAlert);
defer2.resolve(5);

DEMO.

点赞