Skip to content

Instantly share code, notes, and snippets.

@yesvods
Created July 21, 2015 09:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yesvods/01fbeeb39de2c9d16a0a to your computer and use it in GitHub Desktop.
Save yesvods/01fbeeb39de2c9d16a0a to your computer and use it in GitHub Desktop.
ES6 async parallel execution
//mock a fs Object
let fs = {
readFile: function(filename, cb){
let randomTime = 100+Math.random()*1000>>0;
setTimeout(()=>{
cb(`hello ${filename}`)
}, randomTime)
}
}
// wrap fs#readFile into promise
let readFilePro = function(filename){
return new Promise(function(resolve, reject) {
fs.readFile(filename, (data, err) => {
if(err) reject(err);
resolve(data);
})
})
}
//function that execute readFile n times parallel
async function dbFuc(db) {
let tmpArr = Array(10);
tmpArr.fill(10);
let names = tmpArr.map((x,i) => 'file'+i+'.txt');
let promises = names.map((name) => readFilePro(name));
let results = await Promise.all(promises);
console.log(results);
}
//exec
dbFuc();
@jlvertol
Copy link

jlvertol commented Jul 4, 2018

Thank you for sharing this! I needed to get promises working asynchronously with ES6 and I had never done it before. We were working against the clock so your working example was a lifesaver, with just the essentials and no fluff. Perfect!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment