Skip to content

Instantly share code, notes, and snippets.

@bentomas
Created February 10, 2010 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bentomas/300667 to your computer and use it in GitHub Desktop.
Save bentomas/300667 to your computer and use it in GitHub Desktop.
exports.create = function() {
var queue = [],
queueIndex = 0;
// I don't know if we want to save state, but it is easy to implement.
// I am just worried about overhead
var cachedValue = null;
var enqueue = function enqueue(func) {
queue.push(func);
if( cachedValue !== null ) {
fulfill(cachedValue);
}
return enqueue;
};
enqueue.isContinuable = true; // the one hack. so you can know if a returned
// value is itself another continuable
var fulfill = function fulfill(val) {
if( queueIndex < queue.length ) {
// check the return type from the val
if( val instanceof Error ) {
var error = true;
}
else {
var error = false;
}
// in case this was a delayed response, set the cachedValue to null
cachedValue = null;
var returned = queue[queueIndex++](val, !error);
if( typeof returned === 'function' && returned.isContinuable ) {
// need to queue up our function in the continuable
returned(function(val, succeeded) {
fulfill(val);
});
}
// should we make a check for Promises?
else {
fulfill(returned || val);
}
}
else {
cachedValue = val;
}
};
return { 'enqueue': enqueue, 'fulfill': fulfill };
};
var async_function = function(val) {
var cont = continuable.create();
process.nextTick(function() {
cont.fulfill(val);
});
return cont.enqueue;
};
function loadConfig(startVal) {
// uses what you pass in to loadConfig so you can test
// different continuable fulfillment values and how they
// affect the chain
return async_function(startVal)
(function(val, succeeded) {
return succeeded ? val : async_function('{"hello": "world"}');
})
(function(val, succeeded) {
return succeeded ? JSON.parse(val) : val;
});
};
loadConfig(new Error())( function(obj, succeeded) { sys.p(obj) } );
/* Outputs
{
"hello": "world"
}
*/
loadConfig('{"hi":"there"}')( function(obj, succeeded) { sys.p(obj) } );
/* Outputs
{
"hi": "there"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment