Skip to content

Instantly share code, notes, and snippets.

@rchougule
Created September 28, 2020 21:07
Show Gist options
  • Save rchougule/a66c90d72d209ea03ef2192da9858bff to your computer and use it in GitHub Desktop.
Save rchougule/a66c90d72d209ea03ef2192da9858bff to your computer and use it in GitHub Desktop.
Async Waterfall in JavaScript
function selectMovie(input, callback) {
const output = `Movie Selected: ${input} ->`;
callback(null, output);
}
function bookTicket(input, callback) {
const output = `${input}, Ticket ID: 1234 ->`;
callback(null, output);
}
function watchMovie(input, callback) {
const output = `${input} Watching Movie ->`;
callback(null, output);
}
// Utility function for waterfall behaviour
async function waterfall(water, input, callback) {
let result = input;
for (let i = 0; i < water.length; i++) {
result = await new Promise((resolve, reject) => {
water[i](result, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}
callback(null, result);
}
// series execution, passing the result of one function to the next and finally getting the result...
waterfall([selectMovie, bookTicket, watchMovie], "2020", (err, result) => {
console.log(`${result}, Finished watching movie in waterfall...`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment