Skip to content

Instantly share code, notes, and snippets.

@CodeVachon
Last active August 29, 2015 14:27
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 CodeVachon/fe5448e07ed17d1446d9 to your computer and use it in GitHub Desktop.
Save CodeVachon/fe5448e07ed17d1446d9 to your computer and use it in GitHub Desktop.
When To Use a Promise
// ASSUME JQUERY
var document_cache = [];
function getDocument(documentId) {
var _deferred = new $.Deferred()
_document_sent = false; // Note that this could be removed by using `_deferred.state()`
;
// Iterate over the document_cache array
document_cache.forEach(function(thisDocument) {
// If the this is the document being asked for...
if (thisDocument.id == documentId) {
_document_sent = true; // Note that this could be removed by using `_deferred.state()`
// ...Send the document to the caller
_deferred.resolve(thisDocument);
}
});
// If a document has not been sent...
if (!_document_sent) { // Note that this could also be done using `_deferred.state() == 'pending' `
// ...try to get it from the API...
$.get('/path/to/document/api').done(function(fetchedDocument) {
// ...add it the document_cache for later use...
document_cache.push(fetchedDocument);
// ...and return it to the caller
_deferred.resolve(fetchedDocument);
}).fail(_deferred.reject);
}
// return our deffereds promise
return _deferred.promise();
}
$('a.document').on('click', function(e) {
e.preventDefault();
var _working = $("<span>").html("Working Icon");
$(this).append(_working);
// Call our getDocument Function
getDocument($(this).text()).done(function(thisDocument) {
// alert out our selected document
alert(thisDocument);
}).fail(function(error) {
// alert that an error occured
alert(error);
}).always(function() {
// no matter what, remove the working "icon"
_working.remove();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment