Skip to content

Instantly share code, notes, and snippets.

@tcr
Last active December 10, 2015 10:39
Show Gist options
  • Save tcr/4422449 to your computer and use it in GitHub Desktop.
Save tcr/4422449 to your computer and use it in GitHub Desktop.
Logical, simple promises in JavaScript, cause I can never remember this Q business
// Calls functions once a promise has been delivered.
// var p = promise();
// Queue functions: p(yourCallback)
// Deliver the promise: promise.deliver([args...]).
// Once the promise has been delivered, p(yourCallback) immediately calls the callback.
function promise () {
var queue = [], args = null;
var promise = function (fn) {
if (promise.delivered) {
process.nextTick(function () {
fn.apply(null, args);
});
} else {
queue.push(fn);
}
}
promise.deliver = function () {
args = arguments, promise.delivered = true;
queue.splice(0, queue.length).forEach(function (fn) {
process.nextTick(function () {
fn.apply(null, args);
});
});
}
return promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment