Itay Perl
Itay Perl

Reputation: 13524

Propagating progress notifications through $.when

I'm trying to get progress notifications (deferred.notify) to propagate to a promise created by $.when:

var d1 = $.Deferred(),
    d2 = $.Deferred(),
    w  = $.when(d1, d2);

w.progress(function(x) { $('pre').append(String(x)+'\n'); });
d2.notify('d2');
d1.notify('d1');
d2.notify('d2-2');
d1.notify('d1-2');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>

The progress callback sees

undefined
d1
d1
d1-2

What's going on?

Upvotes: 1

Views: 49

Answers (2)

JLRishe
JLRishe

Reputation: 101690

Your progress callback is being called with multiple arguments, one for each promise passed to .when(), but your handler is only accepting one.

The calls are:

undefined   d2          d2.notify('d2')
d1          d2          d1.notify('d1')
d1          d2-2        d2.notify('d2-2')
d1-2        d2-2        d1.notify('d1-2')

If you look at the first column, you will see that's precisely what you're seeing.

var d1 = $.Deferred(),
    d2 = $.Deferred(),
    w  = $.when(d1, d2);

w.progress(function(x, y) { snippet.log(x + ", " + y) });
d2.notify('d2');
d1.notify('d1');
d2.notify('d2-2');
d1.notify('d1-2');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 2

epascarello
epascarello

Reputation: 207511

The arguments are based on the Deferreds attached. So the first one is for d1 and since no message was passed/set previously it is undefined.

var d1 = $.Deferred(),
    d2 = $.Deferred(),
    w  = $.when(d1, d2);

w.progress(function (d1Notify, d2Notify) { 
    var x =  d1Notify + "|" + d2Notify; 
    $('pre').append(String(x)+'\n'); 
});
d2.notify('d2');
d1.notify('d1');
d2.notify('d2-2');
d1.notify('d1-2');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>

Upvotes: 0

Related Questions