Skip to content

Instantly share code, notes, and snippets.

@ericglasser
Created October 30, 2013 19:47
Show Gist options
  • Select an option

  • Save ericglasser/7238997 to your computer and use it in GitHub Desktop.

Select an option

Save ericglasser/7238997 to your computer and use it in GitHub Desktop.
A Pen by Eric Glasser.

Deferred Objects Example

I am using this example to show how deferred objects can be leveraged with setTimeout functions.

A Pen by Eric Glasser on CodePen.

License.

<div id='test1-div'>
test data
</div>
<div id='test2-div'>
test data
</div>
<div id='test3-div'>
test data
</div>
<div id='test-div'>
test data
</div>
var test1 = $.Deferred();
var test2 = $.Deferred();
var test3 = $.Deferred();
var test1Promise = test1.promise();
var test2Promise = test2.promise();
var test3Promise = test3.promise();
var test1Timeout = Math.floor(Math.random()*1000);
var test2Timeout = Math.floor(Math.random()*1000);
var test3Timeout = Math.floor(Math.random()*1000);
setTimeout(function () {
test1.resolve('test1: ' , test1Timeout );
},test1Timeout);
setTimeout(function () {
test2.resolve('test2: ' , test2Timeout );
},test2Timeout);
setTimeout(function () {
test3.reject();
},test3Timeout);
$.when(test1Promise, test2Promise).then(function (test1, test2) {
$('#test-div').html(test1 + ' , ' + test2);
});
var n = 1;
test1Promise.always(function (data) {
$('#test1-div').html('test1 : ' + test1Promise.state() + ' : finsihed ' + n );
n++;
});
test2Promise.always(function (data) {
$('#test2-div').html('test2 : ' + test2Promise.state() + ' : finsihed ' + n);
n++;
});
test3Promise.always(function (data) {
$('#test3-div').html('test3 : ' + test3Promise.state() + ' : finsihed ' + n);
n++;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment