Last active
February 25, 2017 06:51
-
-
Save nsisodiya/a767d7ee09e99460c542298a83f25d26 to your computer and use it in GitHub Desktop.
Promise Based processing with Array. sequentialProcess and parallelProcess
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Author - Narendra Sisodiya - http://narendrasisodiya.com | |
//WHeN to use ? when async result from One Element is needed in another. | |
var sequentialProcess = function(arr, callback){ | |
var pp = Promise.resolve(); | |
arr.forEach(function(v, i, A){ | |
pp = pp.then(function(){ | |
return callback(v, i, A); | |
}); | |
}); | |
return pp; | |
} | |
//WHeN to use ? when async result from One Element is NOT needed in another. | |
var parallelProcess = function(arr, callback){ | |
var pArray = []; | |
arr.forEach(function(v, i, A){ | |
pArray.push(callback(v, i, A)); | |
}); | |
return Promise.all(pArray); | |
} | |
var arr = ["A", "B", "C", "D", "E"]; | |
sequentialProcess(arr, function(val){ | |
console.log("Processing... " + val + " Started") | |
return new Promise(function(resolve){ | |
window.setTimeout(function(){ | |
console.log("Processing " + val + " Done"); | |
resolve(); | |
}, Math.random()*2000+1000) | |
}); | |
}).then(function(){ | |
console.log("ALL Done"); | |
}); | |
/* | |
sequentialProcess Will Result in following. | |
"Processing... A Started" | |
"Processing A Done" | |
"Processing... B Started" | |
"Processing B Done" | |
"Processing... C Started" | |
"Processing C Done" | |
"Processing... D Started" | |
"Processing D Done" | |
"Processing... E Started" | |
"Processing E Done" | |
"ALL Done" | |
*/ | |
/* | |
parallelProcess Will Result in following. | |
"Processing... A Started" | |
"Processing... B Started" | |
"Processing... C Started" | |
"Processing... D Started" | |
"Processing... E Started" | |
"Processing C Done" | |
"Processing A Done" | |
"Processing B Done" | |
"Processing E Done" | |
"Processing D Done" | |
"ALL Done" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment