Created
June 3, 2016 00:14
-
-
Save cdaringe/0646ec485f7f9d3acf5478594545ff7c to your computer and use it in GitHub Desktop.
promise-queue-with-chained-settle-detection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var bluebird = require('bluebird'); | |
var queue; | |
var queueLen = 0; | |
function queueUp(fn) { | |
if (!queue) { | |
console.log('start'); | |
queue = bluebird.resolve(); | |
} | |
++queueLen; | |
queue = queue.then(() => { | |
return bluebird.resolve(fn()).finally(() => { | |
--queueLen; | |
if (!queueLen) console.log('done'); | |
queue = null; | |
}); | |
}); | |
} | |
queueUp(() => console.log(1)); | |
queueUp(() => bluebird.delay(20).then(() => console.log(2))); | |
queueUp(() => bluebird.delay(10).then(() => console.log(3))); | |
setTimeout( | |
() => queueUp(() => console.log(4)), | |
40 | |
); | |
/** | |
* cdieringer@Snapper-osx:~/node/coinstac-common$ node p-queue.js | |
* start | |
* 1 | |
* 2 | |
* 3 | |
* done | |
* start | |
* 4 | |
* done | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment