Skip to content

Instantly share code, notes, and snippets.

@marcelomf
Last active November 18, 2023 14:29
Show Gist options
  • Save marcelomf/5f17982a4e454c3ca91af60d59028090 to your computer and use it in GitHub Desktop.
Save marcelomf/5f17982a4e454c3ca91af60d59028090 to your computer and use it in GitHub Desktop.
Promises em paralelo
const { Runner } = require("./runner");
function funcaoPromise(texto, index) {
const minhaPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(texto+": "+index);
}, 3000);
});
return minhaPromise;
}
async function main() {
const runner = new Runner(funcaoPromise);
for(let i = 0; i < 50; i++) {
runner.addExecution('oi', i);
}
await runner.run(25, function(result) { console.log(result)}, function(err) { console.log(err)});
console.log("FIMMMMMM");
}
main();
/**
Original Author: Caíque Araújo Spósito @kiqaps
Refactoring: Marcelo M. Fleury @marcelomf
*/
class Runner {
constructor(functionPromise) {
this.functionPromise = functionPromise;
}
_executions = []
stop = false
stopRunner() {
this.stop = true
}
addExecution(...args) {
this._executions.push(args)
}
executionCount() {
return this._executions.length
}
async run(groupedBy, onResolve, onReject) {
if (!groupedBy || groupedBy <= 0) {
groupedBy = 1
}
while (this._executions.length > 0 && !this.stop) {
const currentPromises = []
const currentArgs = this._executions.splice(0, groupedBy)
// eslint-disable-next-line no-unused-vars
for (let args of currentArgs) {
currentPromises.push(this.functionPromise(...args).then(onResolve, onReject))
}
await Promise.all(currentPromises)
}
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment