Chaining promises as you're attempting to do here does indeed work as expected, but I do not believe there is any guarantee that done
is called synchronously. I think your code would work, but you have some anti-patterns in it. I would recommend simplifying to avoid explicit creation of the promises.
Also think about: If you call setValue
4 times in a row, how many round-trips to the server should that make? Doing it this way is going to make it take 4. Did you want to batch them into 1 or 2?
One Round Trip Per setValue
:
var _doc = ...;var _pouch = new PouchDB(...);var _updatePromise = Promise.resolve();function setValue(key, value) { // make sure the previous setValue() call is executed completely before // starting another one... _updatePromise = _updatePromise.then(function() { _doc[key] = value; return _pouch.put(_doc) .then(function() { return _pouch.get(_doc._id); }) .then(function(updatedDoc) { _doc = updatedDoc; }); });}