Skip to content

Instantly share code, notes, and snippets.

@MrNyG25
Created June 27, 2023 20:40
Show Gist options
  • Save MrNyG25/8fa14746bfdaa9fceddbaf8f053e5e4e to your computer and use it in GitHub Desktop.
Save MrNyG25/8fa14746bfdaa9fceddbaf8f053e5e4e to your computer and use it in GitHub Desktop.
/**
*
* WITHOUT NESTING
*/
// An asynchronous function that performs a task on each item
/* async function performAsyncTask(item) {
// Simulating an asynchronous task with a delay
await delay(1000);
console.log(`Task completed for item: ${item}`);
} */
// A function that returns a promise after a certain delay
/* function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
} */
// An array of items
//const items = [1, 2, 3, 4];
// Execute the asynchronous tasks on each item using for await...of loop
/* (async () => {
for await (const item of items) {
await performAsyncTask(item);
}
console.log('All tasks completed!');
})(); */
/**
*
* NESTING
*/
// An asynchronous function that performs a task on each letter
async function performAsyncTask(letter) {
// Simulating an asynchronous task with a delay
await delay(3000);
console.log(`Task completed for letter: ${letter}`);
}
// A function that returns a promise after a certain delay
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// An array of letters
const letters = ['a', 'b', 'c'];
// Execute the nested asynchronous tasks using for await...of loops
(async () => {
for await (const letter of letters) {
console.log(`Processing letter: ${letter}`);
const nestedLetters = [1, 2, 3];
for await (const nestedLetter of nestedLetters) {
await performAsyncTask(nestedLetter);
}
console.log(`Nested tasks completed for letter: ${letter}`);
}
console.log('All tasks completed!');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment