Created
July 21, 2015 09:11
-
-
Save yesvods/01fbeeb39de2c9d16a0a to your computer and use it in GitHub Desktop.
ES6 async parallel execution
This file contains 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
//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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!