Created
February 22, 2018 20:31
-
-
Save spidgorny/f2c3fb6aa4a54c506ff927c19b45afbe to your computer and use it in GitHub Desktop.
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
function analyze(i, callback) { | |
setTimeout(() => { | |
callback('result 123'); | |
}, Math.random()*10000); | |
// long thinking time.... | |
// callback('result 123'); | |
} | |
async function analyzeAsync(i) { | |
return new Promise((resolve, reject) => { | |
analyze(i, (result) => { | |
console.log('ready', i); | |
resolve({ | |
[i]: result | |
}); | |
}); | |
}); | |
} | |
async function sendDataAsync(param1, param2) { | |
return new Promise((resolve, reject) => { | |
sendData(param1, param2, (result) => { | |
// process results | |
resolve(result); | |
}); | |
}); | |
} | |
const data = [ | |
6, 1, 2, 3, 4, 5, | |
]; | |
function callMeAfterAnalyze(data) { | |
// use data | |
} | |
analyze(5, callMeAfterAnalyze); | |
analyze(5, (data) => { | |
// use data | |
}); | |
let total = {}; | |
// takes 5 sec | |
(async () => { | |
console.log('Slow...'); | |
console.time('slow'); | |
for (let i of data) { | |
console.log(i); | |
let result = await analyzeAsync(i); // <- stop here | |
// process results | |
console.log('result', result); | |
total[i] = result; | |
} | |
console.log('done', total); | |
console.timeEnd('slow'); | |
console.log('Fast'); | |
// takes 1 sec | |
console.time('fast'); | |
const setOfPromises = []; | |
for (let i of data) { | |
console.log(i); | |
setOfPromises.push(analyzeAsync(i)); | |
// process results | |
} | |
console.log('loop done, '); | |
const results = await Promise.all(setOfPromises); // wait for all 5 requests at once | |
console.log(results); | |
console.timeEnd('fast'); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment