Created
March 17, 2017 18:28
-
-
Save sebcode/322a8b54bbcbaf1dabe04401ddb9e6c2 to your computer and use it in GitHub Desktop.
nodejs: Execute multiple tasks in parallel
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
#!/usr/bin/env node | |
const async = require('async') | |
const numTasks = 10 | |
const numParallel = 4 | |
function doTask(i) { | |
console.log(`${i} start`) | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
console.log(`${i} end`) | |
resolve(i) | |
}, 1000) | |
}) | |
} | |
async function run() { | |
const tasks = [...Array(numTasks).keys()].map(i => { | |
return cb => { | |
return doTask(i) | |
.then(res => cb(null, res)) | |
.catch(err => cb(err)) | |
} | |
}) | |
await new Promise((resolve, reject) => { | |
async.parallelLimit(tasks, numParallel, (err, result) => { | |
if (err != null) { | |
reject(err) | |
return | |
} | |
resolve(result) | |
}) | |
}) | |
console.log('done') | |
} | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment