Implement an async waterfall function in javascript. An async waterfall function is a function that get two parameters: Tasks - An array of async functions to run. Each function should complete with any number of result values. The result values will be passed as arguments, in order, to the next task. callback - A callback to run once all the functions have completed. This will be passed the results of the last task's callback. Invoked with (err, [results]). The tasks from should run one after the other asynchronously. A call to this function should look like this: AsyncWaterfall([ function One(callback) { console.log("One called with", arguments) callback(null, 'one', 'two', 'three', 'four'); }, function Two(arg1, arg2, arg3, arg4, callback) { console.log("Two called with", arguments) // arg1 now equals 'one' and arg2 now equals 'two' setTimeout(function () { callback(null, 'three'); }, 1500) }, function Three(arg1, callback) { console.log("Three called with", arguments) // arg1 now equals 'three' callback(null, 'done'); }, ], function Done(err, result) { if (err) { console.log("Error!", err) } else { console.log("Done", result) } });
Anonymous
Write a helper function that use recursion, so that each task function should call the next task function: function AsyncWaterfall(tasks, callback) { let index = 0; function handleTask(err, ...args) { if (err || index === tasks.length) { callback(err, ...args); return } tasks[index++](...args, handleTask) } handleTask(); }
Check out your Company Bowl for anonymous work chats.