Skip to content

Instantly share code, notes, and snippets.

@rileydutton
Created November 16, 2016 15:07
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 rileydutton/69759173562ad05523672ac2a40df49f to your computer and use it in GitHub Desktop.
Save rileydutton/69759173562ad05523672ac2a40df49f to your computer and use it in GitHub Desktop.
var asyncWaterfall = function (tasks, cb) {
var current = 0
function done (err, args) {
function end () {
args = args ? [].concat(err, args) : [ err ]
if (cb) cb.apply(undefined, args)
}
end();
}
function each (err) {
var args = Array.prototype.slice.call(arguments, 1)
if (++current >= tasks.length || err) {
done(err, args)
} else {
tasks[current].apply(undefined, [].concat(args, each))
}
}
if (tasks.length) {
tasks[0](each)
} else {
done(null)
}
};
on("change:test1", function() {
asyncWaterfall([
function(callback) {
log("Waterfall One");
getAttrs(["test1"], function(vals) {
log("Got attributes");
callback(null, vals);
});
},
function(prevvals, callback) {
log("Waterfall Two");
setAttrs({
test2: parseInt(prevvals.test1, 10) + 5
}, {}, function() {
log("DONE with Set attributes");
callback(null);
});
},
function(callback) {
log("Waterfall Three");
callback(null);
}
], function() {
log("Waterfall completed!");
})
});
@Lithl
Copy link

Lithl commented Feb 25, 2017

Thanks for this, Riley. Steve linked me here thinking that it might offer me a solution to a problem, and I managed to rewrite it to suit my needs. My use-case essentially required treating the tasks array like a stack, so instead of iterating over the array with a closed-over index variable, I'm shift()ing and unshift()ing values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment