Last active
December 10, 2015 10:39
-
-
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
This file contains 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
// 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