From d672f9221b5eeac03b12ca99445ec1457a4a3a94 Mon Sep 17 00:00:00 2001 From: Mathieu Dutour Date: Thu, 14 Jul 2016 07:07:51 +0100 Subject: [PATCH] wait for the last 'each' (in ) to or before resolving the promise --- History.md | 4 ++++ lib/collection.js | 29 ++++++++++++++++++++++++----- package.json | 2 +- test/collection.js | 9 ++++++--- 4 files changed, 35 insertions(+), 9 deletions(-) diff --git a/History.md b/History.md index e1aa1cd4..22c8993a 100644 --- a/History.md +++ b/History.md @@ -1,3 +1,7 @@ +3.0.7 / 2016-07-14 +================== + - Wait for the last 'each' (in `find`) to `resume` or `close` before resolving the promise + 3.0.6 / 2016-07-11 ================== - Fix when casting `null` diff --git a/lib/collection.js b/lib/collection.js index 981e638b..9214600d 100644 --- a/lib/collection.js +++ b/lib/collection.js @@ -345,28 +345,47 @@ Collection.prototype.find = function (query, opts, fn) { } var didClose = false + var didFinish = false + var processing = 0 function close () { didClose = true + processing -= 1 cursor.close() } + function pause () { + processing += 1 + cursor.pause() + } + return new Promise(function (resolve, reject) { cursor.on('data', function (doc) { if (!didClose) { promise.eachListener(doc, { close: close, - pause: cursor.pause.bind(cursor), - resume: cursor.resume.bind(cursor) + pause: pause, + resume: resume }) } }) + function resume () { + processing -= 1 + cursor.resume() + if (processing === 0 && didFinish) { + done() + } + } + function done () { - if (fn) { - fn() + didFinish = true + if (processing <= 0) { + if (fn) { + fn() + } + resolve() } - resolve() } cursor.on('close', done) diff --git a/package.json b/package.json index b1346e78..12436c1e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "monk", - "version": "3.0.6", + "version": "3.0.7", "main": "lib/monk.js", "tags": [ "mongodb", diff --git a/test/collection.js b/test/collection.js index 1540ebd0..f4cb3604 100644 --- a/test/collection.js +++ b/test/collection.js @@ -308,12 +308,15 @@ test('find > stream pause and continue', (t) => { pause() const duration = Date.now() - start t.true(duration > index * 1000) - index += 1 - setTimeout(resume, 1000) + setTimeout(() => { + index += 1 + resume() + }, 1000) }) .then(() => { + t.is(index, 4) const duration = Date.now() - start - t.true(duration > 3000) + t.true(duration > 4000) }) }) })