Skip to content

Instantly share code, notes, and snippets.

@ScreamZ
Last active November 4, 2019 22:46
Show Gist options
  • Save ScreamZ/a638493ed75cac6b12882637c7e7d95e to your computer and use it in GitHub Desktop.
Save ScreamZ/a638493ed75cac6b12882637c7e7d95e to your computer and use it in GitHub Desktop.
const chalk = require("chalk").default;
// Fail after time
function ApiError(time, theme) {
return new Promise((_, reject) => {
setTimeout(() => {
reject("=> API call " + chalk.red("failed") + " with [" + chalk.blue(theme) + "] at " + time);
}, time);
});
}
// Block execution and succeed after time
function createFile(time, theme) {
return new Promise(resolve => {
setTimeout(() => {
resolve("=> Created file for [" + chalk.blue(theme) + "]");
}, time);
});
}
// Succeed after time
function ApiSuccess(time, theme) {
return new Promise(resolve => {
setTimeout(() => {
resolve("=> Succeed API call on [" + chalk.blue(theme) + "]");
}, time);
});
}
// Loop occurence
async function loopOccurence(currentTheme) {
const loopJobName = chalk.green("✅ Finished job [" + chalk.blue(currentTheme) + "] at");
// Starting timer for counting duration of loop
console.time(loopJobName);
try {
console.log(`=> API call [${chalk.blue(currentTheme)}] is started`);
// To make some task fails and some work 50% chances.
const randomBooleanTrue = Math.random() >= 0.5;
if (randomBooleanTrue) {
await ApiError(3000, currentTheme);
} else {
const result = await ApiSuccess(3000, currentTheme);
console.log(result);
}
// If API succeeded, create file action
const writeOperationResult = await createFile(2000, currentTheme);
console.log(writeOperationResult);
// End timer
console.timeEnd(loopJobName);
} catch (error) {
console.log(error);
// End timer
console.timeEnd(loopJobName);
}
}
(async () => {
try {
const programExecutionTimer = chalk.green("✅ Reached end of script time");
const themes = ["sport", "cooking", "education"];
// Starting timer for script execution duration
console.time(programExecutionTimer);
console.log(chalk.blueBright("🚀 Starting synchronous script execution"));
// 1st case : Synchronous loop that wait at each occurence
for (let currentTheme of themes) {
await loopOccurence(currentTheme);
}
// 2nd case: asynchronous loop that use parallelism
// for (let currentTheme of themes) {
// loopOccurence(currentTheme);
// }
// 3rd case: asynchronous loop that use parallelism using functional programming
// themes.forEach(loopOccurence);
// 4th case: Even better and most efficient way
// await Promise.all(themes.map(loopOccurence));
// End timer for script execution duration
console.timeEnd(programExecutionTimer);
} catch (error) {
console.log(error);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment