Waterfall dependent mono-tasking
suggest changeasync.waterfall(tasks, afterTasksCallback) runs tasks one after another and passes each task's result to the next task. If a task fails, async stops and calls the final callback with that error.
When every task succeeds, that callback gets the value passed by the last task, not the results of every task.
function getUserRequest(callback) {
// We simulate the request with a timeout
setTimeout(function() {
var userResult = {
name : 'Aamu'
};
callback(null, userResult);
}, 500);
}
function getUserFriendsRequest(user, callback) {
// Another request simulate with a timeout
setTimeout(function() {
var friendsResult = [];
if (user.name === "Aamu"){
friendsResult = [{
name : 'Alice'
}, {
name: 'Bob'
}];
}
callback(null, friendsResult);
}, 500);
}
async.waterfall([
getUserRequest,
getUserFriendsRequest
],
function(err, results) {
if (err) {
return console.error(err);
}
console.log(JSON.stringify(results));
});
Result: results contains the second callback parameter of the last function of the waterfall, which is friendsResult in that case.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents