Skip to content

Instantly share code, notes, and snippets.

@lot224
Created May 16, 2016 17:34
Show Gist options
  • Save lot224/c80243ce33de417d55b500626e104ea3 to your computer and use it in GitHub Desktop.
Save lot224/c80243ce33de417d55b500626e104ea3 to your computer and use it in GitHub Desktop.
Angular, reuse a $q promise if not resolved.
var factoryItem = ["$q", function ($q) {
var factory = {};
var pendingPromises = {};
factory.test = function (identifier) {
// Assigns d to the variable that will contain the promise if pending.
var d = pendingPromises[identifier];
// Check to see if d is not null or undefined, and checks to
// see if the promise's state's status is 0 (not resolved/rejected)
if (d && d.promise.$$state.status === 0) {
console.log("Promise already pending, return it.");
return d.promise;
}
console.log("Pending promise not found, create a new one.");
d = pendingPromises[identifier] = $q.defer();
// Create a 5 second delay before resolving the promise simulating an AJAX call
setTimeout(function () {
d.resolve("Promise has been resolved.");
}, 5000);
// Return the new promise.
return d.promise.finally(function () {
// clean up the collection object since the promise was resolved/rejected.
console.log("Promise resolved/rejected, purge the promise from the collection.");
delete pendingPromises[identifier];
});
};
return factory;
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment