Skip to content

Instantly share code, notes, and snippets.

@shamansir
Created February 22, 2012 08:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shamansir/1883358 to your computer and use it in GitHub Desktop.
Save shamansir/1883358 to your computer and use it in GitHub Desktop.
Easy Deferrables For JavaScript
/* See also: http://cl.ly/0Q1n1P0R223E1224332M/o */
/* the main trick */
function deferrable(f) {
return function() {
return (function(f, args) {
return function() {
return f.apply(null, args);
};
})(f, arguments);
}
}
/* the function we want to be deferred */
function read_file(name) {
console.log('reading ' + name);
return name !== 'foo.js'; // success when name's not `foo.js`
}
/* some function that executes a list of another
function in a smart way
prepares them, breaks them, anything... */
function smart_exec() {
var fs = arguments, // array of functions
flen = fs.length;
for (var i = 0; i < flen; i++) {
if (!fs[i]()) return; // if function not succeeded, stop the process
};
}
/* we may emulate smart "break queue if failed" using && operator
or smart "break on first success" using || operator,
but that'all.
notice that `read_file('c')` is not executed here. */
read_file('a') && read_file('b') && read_file('foo.js') && read_file('c');
// > reading a
// > reading b
// > reading foo.js
// < false
/* we may use smart_exec in a way like this, but it looks like a crap
yes, we may pass a list of files to some function and read them inside,
but then we may call it not `smart_exec`, but rather `smart_read_file` */
smart_exec(function() { return read_file('a') }, function() { return read_file('b') },
function() { return read_file('foo.js') }, function() { return read_file('c') });
// > reading a
// > reading b
// > reading foo.js
// < undefined
/* and so we transform `read_file` into deferrable... */
read_file = deferrable(read_file);
/* ... cool enough, isn't it?
notice that `read_file('c')` is not executed here... */
smart_exec(read_file('a'), read_file('b'), read_file('foo.js'), read_file('c'));
// > reading a
// > reading b
// > reading foo.js
// < undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment