Skip to content

Instantly share code, notes, and snippets.

@tony-0tis
Last active June 24, 2024 10:00
Show Gist options
  • Save tony-0tis/81cb708f0ef01ed2d3ecf6e6aae43013 to your computer and use it in GitHub Desktop.
Save tony-0tis/81cb708f0ef01ed2d3ecf6e6aae43013 to your computer and use it in GitHub Desktop.
A simple script to run asynchronous tasks sequentially. Alternative to async.waterfall

0tis-waterfall

A simple script to run asynchronous tasks sequentially. Alternative to async.waterfall

Install

npm i -S gist:81cb708f0ef01ed2d3ecf6e6aae43013

How to use

import waterfallTasks from '0tis-waterfall';
waterfallTasks([
  cb=>{
    const error = null;
    const data1 = 'good';
    const data2 = 'day';
    cb(error, data1, data2);//the first parameter is always an error, the other parameters will be passed to the next task.
  },
  (cb, data1, data2)=>{
    cb();
  }
], (err, data)=>{
  //do finally task
});
{
"version": "0.1.0",
"name": "0tis-waterfall",
"main": "waterfallTasks.mjs"
}
async function waterfallTasks(tasks, callback){
if(!Array.isArray(tasks)) {
console.error('First argument must be an array');
return;
}
let result = [];
let err = null;
for(let task of tasks){
if(typeof task !== 'function') {
console.error(`task is not a function: ${task}\nwaterfall continues to run`);
continue;
}
[...result] = await new Promise(resolve=>{
try{
task((...array)=>{
resolve([...array])
}, ...result);
}catch(e){
resolve([e]);
}
});
err = result.splice(0, 1)[0];
if(err){
console.error(err);
break;
}
}
if(typeof callback === 'function') callback(err, result);
}
export default waterfallTasks;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment