Last active
March 2, 2021 12:03
-
-
Save krishnaTORQUE/6e5b67cb367a7340d1517ad13d67e09a to your computer and use it in GitHub Desktop.
Nodejs parallel check
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
/** | |
* Long Function | |
* It will take 2 seconds to resolve | |
*/ | |
const longFunc = async () => { | |
const second = 2; | |
return new Promise((solve) => { | |
setTimeout(() => { | |
console.log('Hello World'); | |
solve(true); | |
}, 1000 * second); | |
}); | |
}; | |
/** | |
* Number of iteration | |
*/ | |
const noi = 8; | |
/** | |
* Async / Parallel Programming | |
*/ | |
const asyncFunc = async () => { | |
let promiseArr = []; | |
for (let i = 0; i < noi; i++) promiseArr.push(longFunc()); | |
await Promise.all(promiseArr); | |
}; | |
/** | |
* Synchronize Programming | |
*/ | |
const syncFunc = async () => { | |
for (let i = 0; i < noi; i++) await longFunc(); | |
}; | |
/** | |
* Main | |
*/ | |
(async () => { | |
const startTime = Date.now(); | |
/** | |
* Async / Parallel or Synchronize Function NAME to run test | |
* Does the same job but huge difference in efficient & performance | |
*/ | |
await asyncFunc(); // takes 2 seconds | |
// await syncFunc(); // takes 16 seconds | |
const endTime = Date.now(); | |
console.log(`Iteration: ${noi} | ${(endTime - startTime) / 1000} seconds`); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment