Last active
December 13, 2019 07:07
-
-
Save ebta/cda21f46e901c60abc40714d035502c3 to your computer and use it in GitHub Desktop.
Example using async library for paralel or series
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
// 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