Skip to content

Instantly share code, notes, and snippets.

@andyhasit
Last active March 16, 2016 21:31
Show Gist options
  • Save andyhasit/4db75f6727adf011615a to your computer and use it in GitHub Desktop.
Save andyhasit/4db75f6727adf011615a to your computer and use it in GitHub Desktop.
/*
Wraps a db object such as PouchDB instance (currently just: post put get remove)
And ensures those actions, which are promises, resolve in the order they were called.
Essentially creates a synchronous interface to a db.
*/
app.factory('QueuedResponseDb', function($q, ValueRegister) {
var QueuedResponseDb = function(db) {
var self = this;
self._db = db;
self.queue = {};
self._nextId = 0;
self._latestResolvedId = 1;
self.wrapPromise = function(dbCall, data) {
var promiseId = self.nextId();
var hiddenPromise = self._db[dbCall](data);
var returnPromise = $q.defer();
self.queuePromise(promiseId, returnPromise);
hiddenPromise.then(function(response) {
self.promiseGotResolved(promiseId, response);
});
return returnPromise.promise;
};
angular.forEach(['post', 'put', 'get', 'remove'], function (dbCall) {
self[dbCall] = function(data) {
return self.wrapPromise(dbCall, data);
}
});
};
QueuedResponseDb.prototype.nextId = function (){
this._nextId ++;
return this._nextId;
}
QueuedResponseDb.prototype.queuePromise = function(promiseId, returnPromise) {
this.queue[promiseId] = {
returnPromise: returnPromise,
resolved: false
};
};
QueuedResponseDb.prototype.promiseGotResolved = function(promiseId, result) {
var promise = this.queue[promiseId]
promise['result'] = result;
promise.resolved = true;
this.releasResolvedPromises();
};
QueuedResponseDb.prototype.releasResolvedPromises = function() {
var stop = false; // encounteredUnresolvedPromiseOrReachedEndOfQueue
while (!stop) {
entry = this.queue[this._latestResolvedId]
if (entry && entry.resolved) {
entry.returnPromise.resolve(entry.result);
this._latestResolvedId ++;
} else {
stop = true;
}
}
}
return QueuedResponseDb;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment