Skip to content

Commit

Permalink
wait for the last 'each' (in ) to or before resolving the promise
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieudutour committed Jul 14, 2016
1 parent 30b14d2 commit d672f92
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 9 deletions.
4 changes: 4 additions & 0 deletions History.md
Original file line number Diff line number Diff line change
@@ -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`
Expand Down
29 changes: 24 additions & 5 deletions lib/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "monk",
"version": "3.0.6",
"version": "3.0.7",
"main": "lib/monk.js",
"tags": [
"mongodb",
Expand Down
9 changes: 6 additions & 3 deletions test/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})
})
Expand Down

0 comments on commit d672f92

Please sign in to comment.