Adam
Adam

Reputation: 4227

jQuery progress repeated calls when using $.when

I am using jQuery deferreds, and have noticed an odd behavior.

See fiddle here: http://jsfiddle.net/wKTgP/1/

If I use $.when to call a set of promises

$.when(promise1, promise2)
    .progress(function (message1, message2) {
        alert(message1 + ' ' + message2);
    });

If promise1 sends a notification 'hello', and promise2 sends 'world', I get two message boxes:

'hello undefined'

and

'hello world'

The first notification obviously shows a message from promise1, and promise2 hasnt sent anything yet... but the SECOND notification makes me think that promise1 has sent 'hello' AGAIN, and promise2 is sending 'world' for the first time...

What's the story with this?

Upvotes: 1

Views: 419

Answers (1)

Julian Aubourg
Julian Aubourg

Reputation: 11436

Keep in mind that, when you're attaching a progress handler to a promise that already progressed, the callback is called immediately with the latest progress value:

$.Deferred().notify( "hello" ).progress(function( value ) {
    console.log( value );
});

Will log "hello" immediately.

Now, $.when returns a compound promise. So, everytime one of its components progresses, the compound promise progresses.

Given that the latest notification value is kept "in memory" and that the compound promise returned by $.when progresses when one of its component progresses, then it makes perfect sense that the progress value should be the union of all of the joined promises progress values, even if and when only one progressed:

[ "hello", undefined ]
[ "hello", "world" ]

Upvotes: 4

Related Questions