Last active
February 20, 2022 22:10
-
-
Save ashutoshpw/a4f5292b2960a9955585a5f10a23891c to your computer and use it in GitHub Desktop.
Foreach with Promise.all for faster execution than For Loop
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
module.exports = [ | |
{ | |
id:1, | |
data:1 | |
}, | |
{ | |
id:2, | |
data:2 | |
}, | |
{ | |
id:3, | |
data:3 | |
}, | |
{ | |
id:4, | |
data:4 | |
}, | |
{ | |
id:5, | |
data:5 | |
}, | |
{ | |
id:6, | |
data:6 | |
}, | |
{ | |
id:7, | |
data:7 | |
}, | |
{ | |
id:8, | |
data:8 | |
}, | |
{ | |
id:9, | |
data:9 | |
}, | |
{ | |
id:10, | |
data:10 | |
} | |
] |
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
let object = require('./data'); | |
let CONSTANTS = { | |
TIMEOUT:100 | |
} | |
(async()=>{ | |
let promise3 = async () =>{ | |
return new Promise(function(resolve, reject) { | |
setTimeout(resolve, CONSTANTS.TIMEOUT, 'foo'); | |
}); | |
} | |
let start_time = new Date().getTime(); | |
for(let i=0; i<object.length; i++){ | |
object[i]['data'] = object[i]['data'] + 2; | |
await promise3(); | |
console.log("LOOP",i); | |
}; | |
let end_time = (new Date()).getTime(); | |
console.log("EXECUTION TIME",(end_time-start_time)); | |
console.log("DATA",object); | |
})(); | |
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
let object = require('./data'); | |
let CONSTANTS = { | |
TIMEOUT:100 | |
} | |
let promises = []; | |
let two_start = (new Date()).getTime(); | |
object.forEach(o=>{ | |
promises.push( | |
new Promise((resolve, reject)=>{ | |
//resolve(1); | |
o['data'] = o['data'] + 2; | |
setTimeout(resolve(o), CONSTANTS.TIMEOUT); | |
}) | |
); | |
}); | |
Promise.all(promises).then(x=>{ | |
let MODIFIED_DATA = x; | |
let two_end = (new Date()).getTime(); | |
console.log("EXECUTION TIME",(two_end-two_start)); | |
console.log("DATA", MODIFIED_DATA) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment