Skip to content

Instantly share code, notes, and snippets.

@nmvuong92
Last active December 19, 2018 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmvuong92/808a3c2a00b0d268a71e4f01ee975354 to your computer and use it in GitHub Desktop.
Save nmvuong92/808a3c2a00b0d268a71e4f01ee975354 to your computer and use it in GitHub Desktop.
Deffered in jquery

First: You cannot use $.Promise(); because it does not exist. A deferred object is an object than can create a promise and change its state to resolved or rejected. Deferreds are typically used if you write your own function and want to provide a promise to the calling code. You are the producer of the value.

A promise is, as the name says, a promise about a future value. You can attach callbacks to it to get that value. The promise was "given" to you and you are the receiver of the future value. You cannot modify the state of the promise. Only the code that created the promise can change its state.

Examples:

  1. (produce) You use deferred objects when you want to provide promise-support for your own functions. You compute a value and want to control when the promise is resolved.
function callMe() {    
  var d = new $.Deferred();    
  setTimeout(function() {        
  	d.resolve('some_value_compute_asynchronously');   
  }, 1000); 
  return d.promise();
}
callMe().done(function(value) { 
	alert(value);
});
  1. (forward) If you are calling a function which itself returns a promise, then you don't have to create your own deferred object. You can just return that promise. In this case the function does note create a value, but forwards it (kind of):
function fetchData() {    
  // do some configuration here and pass to `$.ajax`   
  return $.ajax({...});
}
fetchData().done(function(response) { 
	// ...
});
  1. (receive) Sometimes you don't want to create or pass along promises/values, you want to use them directly, i.e. you are the receiver of some information:
$('#my_element').fadeOut().promise().done(function() {    // called when animation is finished});

Of course all these use cases can be mixed as well. Your function can be the receiver of a value (from an Ajax call for example) and compute (produce) a different value based on that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment