Skip to content

Instantly share code, notes, and snippets.

@d6u
Created March 10, 2015 04:25
Show Gist options
  • Select an option

  • Save d6u/ca5e60cdab44a623d95a to your computer and use it in GitHub Desktop.

Select an option

Save d6u/ca5e60cdab44a623d95a to your computer and use it in GitHub Desktop.
var Bluebird = require('bluebird');
function Something() {
this.queue = [];
this.currentJob = null;
}
Something.prototype.queueJob = function (job) {
if (this.currentJob) {
this.queue.push(job);
} else {
this.currentJob = Bluebird.bind(this)
.then(job)
.then(function () {
this.currentJob = null;
if (this.queue.length) {
var self = this;
setImmediate(function () {
self.queueJob(self.queue.shift());
});
}
});
}
};
Something.prototype.sayHello = function () {
this.queueJob(function () {
return new Bluebird(function (resolve, reject) {
setTimeout(function () {
console.log('Hello');
resolve();
}, 500);
});
});
return this;
};
Something.prototype.sayHello2 = function () {
this.queueJob(function () {
return new Bluebird(function (resolve, reject) {
setTimeout(function () {
console.log('Hello2');
resolve();
}, 500);
});
});
return this;
};
var thing = new Something();
thing.sayHello().sayHello().sayHello2().sayHello2().sayHello();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment