Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cdaringe/0646ec485f7f9d3acf5478594545ff7c to your computer and use it in GitHub Desktop.
Save cdaringe/0646ec485f7f9d3acf5478594545ff7c to your computer and use it in GitHub Desktop.
promise-queue-with-chained-settle-detection
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