Skip to content

Instantly share code, notes, and snippets.

@Isan-Rivkin
Created November 5, 2018 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Isan-Rivkin/61ffb135b4e47619946b61724b8f25d1 to your computer and use it in GitHub Desktop.
Save Isan-Rivkin/61ffb135b4e47619946b61724b8f25d1 to your computer and use it in GitHub Desktop.
parallel and waterfall batch execution
// parallel batch computation with callback in the end
const parallel = require('async/parallel');
// sequential batch computation with callback in the end
const waterfall = require('async/waterfall');
// all the tasks below run at the same time
function computerParallelBatch(){
parallel([
cb=>{
setTimeout(()=>{
let val = 1000;
let error = null;
cb(error, val);
},1000);
},
cb=>{
setTimeout(()=>{
let val = 800;
let error = null;
cb(error, val);
},800);
},
cb=>{
setTimeout(()=>{
let val = 1500;
let error = null;
cb(error, val);
},1500);
},
cb=>{
setTimeout(()=>{
let val = 200;
let error = null;
cb(error, val);
},200);
},
],(err,results)=>{
if(err){
console.log("some err ", err);
}else{
console.log("all results = " + results);
}
});
}
function computeAsyncDependentBatch() {
waterfall([
// task 1
cb => {
setTimeout(() => {
let val = 300;
cb(null,val);
}, 300);
},
// task 2 (after task 1 sequential)
(val,cb)=> {
setTimeout(() => {
console.log("previous val : " + val);
cb(null,[1,2,3,4,5]);
}, 100);
}
// end of tasks, final callback
], (err, values) => {
if(err){
console.log("error " , err);
}else{
console.log("no error " , values);
}
});
}
// test 1 - parallel batch
computerParallelBatch();
// test 2 - sequential batch
computeAsyncDependentBatch();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment