Created
November 16, 2016 15:07
-
-
Save rileydutton/69759173562ad05523672ac2a40df49f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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!"); | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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'mshift()
ing andunshift()
ing values.