Skip to content

Instantly share code, notes, and snippets.

@ebta
Last active December 13, 2019 07:07
Show Gist options
  • Save ebta/cda21f46e901c60abc40714d035502c3 to your computer and use it in GitHub Desktop.
Save ebta/cda21f46e901c60abc40714d035502c3 to your computer and use it in GitHub Desktop.
Example using async library for paralel or series
// Doc Async : https://caolan.github.io/async/v3/index.html
// Download : http://www.jsdelivr.com/projects/async
function task(item, callback) {
setTimeout(function() {
console.info(item + ' selesai');
// null menandakan fungsi berhasil
callback(null, item * 3);
// jika gagal atau error, return dengan selain null
// misal : callback('error','keterangan error');
}, 100);
}
var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
// data akan di kerjakan secara paralel 3-3-3..
async.mapLimit(data, 3, function(item, done) {
task(item,done);
}, function(err, results) {
// senua data telah selesai di proses
console.log(results);
// results =  [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33]
});
// kalau ingin dikerjakan secara serries
async.mapSeries(data, function(item, done) {
task(item,done);
}, function(err, results) {
// senua data telah selesai di proses
console.log(results);
});
// Menggunakan each
async.eachLimit(data, 4, function(item, done) {
task(item,done);
}, function(err, results) {
console.log('each', results);
// results = undefined ( ini perbedaan dengan async.map )
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment