Skip to content

Instantly share code, notes, and snippets.

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

0tis-autotasks

A simple script to run asynchronous tasks with auto. Alternative to async.auto

Install

npm i -S gist:bf5ff86a2a20f88f3b327872427598ab

How to use

import autoTasks from '0tis-autotasks';
autoTasks({
  one: cb=>cb(null, 1),
  two:['one', (cb, res)=>cb(null, res.one, 2)],
  three: ['one', 'two', (cb, res)=>cb('just error')]
}, (err, data)=>{
  console.log(err, data); //just error {one: 1, two: [1, 2], three: undefined}
})
function autoTasks(tasks, callback){
if(tasks == null) {
throw new Error('First argument must be an object (but not null)');
}
const toDo = [];
const wait = {};
const results = {};
let done = false;
const call = (key, task, resolve, reject)=>{
[task] = task;
try{
task((err, ...result)=>{
if(done) return;
if(result.length < 2) [result] = result;
results[key] = result;
if(err){
return reject(err);
}
resolve();
if(wait[key]){
wait[key].forEach(check=>check());
}
while(run = toDo.shift()){
run();
}
}, results);
}catch(e){
reject(e);
}
};
Promise.all(Object.keys(tasks).map(key=>{
return new Promise((resolve, reject)=>{
let task = tasks[key];
if(!Array.isArray(task)) task = [task];
let dependencies = task.splice(0, task.length-1);
if(dependencies.length){
dependencies.forEach(dependency=>{
if(!tasks[dependency]){
throw new Error(`Task "${key}" have dependency "${dependency}" that not presented in object`);
}
if(!wait[dependency]) wait[dependency] = [];
wait[dependency].push(()=>{
dependencies = dependencies.filter(dep=>dep !== dependency);
if(!dependencies.length){
toDo.push(()=>call(key, task, resolve, reject));
}
});
});
}
else{
toDo.push(()=>call(key, task, resolve, reject));
}
});
})).then(()=>{
done = true;
callback(null, results);
}).catch(e=>{
done = true;
callback(e, results);
});
while(run = toDo.shift()){
run();
}
}
export default autoTasks;
{
"version": "0.1.0",
"name": "0tis-autotasks",
"main": "autoTasks.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment