diff --git a/lib/client/doc.js b/lib/client/doc.js index b8c700de2..dd702eace 100644 --- a/lib/client/doc.js +++ b/lib/client/doc.js @@ -295,7 +295,7 @@ Doc.prototype._handleFetch = function(error, snapshot) { var callbacks = this.pendingFetch; this.pendingFetch = []; var callback = this.inflightFetch.shift(); - if (callback) callbacks.push(callback); + if (callback) callbacks.unshift(callback); if (callbacks.length) { callback = function(error) { util.callEach(callbacks, error); diff --git a/test/client/doc.js b/test/client/doc.js index 523561ec4..4156ab4a1 100644 --- a/test/client/doc.js +++ b/test/client/doc.js @@ -101,6 +101,27 @@ describe('Doc', function() { doc.fetch(finish); doc.fetch(finish); }); + it('callbacks called in correct order when fetching and applying ops in quick succession', function(done) { + var connection = this.connection; + var doc = connection.get('dogs', 'fido'); + doc.create({name: 'fido'}); + var order = ''; + doc.fetch(function() { + order += 'A'; + }); + doc.submitOp([{p: ['snacks'], oi: true}]); + doc.fetch(function() { + order += 'B'; + }); + doc.submitOp([{p: ['color'], oi: 'gray'}]); + doc.fetch(function() { + order += 'C'; + }); + doc.whenNothingPending(function() { + expect(order).to.eql('ABC'); + done(); + }); + }); }); describe('when connection closed', function() {