Skip to content

Instantly share code, notes, and snippets.

@CodeVachon

CodeVachon/get_document.js

Last active Aug 29, 2015
Embed
What would you like to do?
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