?? JavaScript Loops & Async Code: A Roller Coaster Ride ??
Looping through arrays in JavaScript is like riding a roller coaster — it’s fun, a little unpredictable, and sometimes a bit dizzying! ?? But when you throw asynchronous code into the mix? Well, things get really interesting. Let's dive into the wild world of loops and async in JavaScript!
The Looping Basics ??
JavaScript loops are essential for repeating tasks, but throw in async code, and things get interesting! Let’s break it down quickly.
for (let i = 0; i < 5; i++) {
console.log(i); // Prints 0, 1, 2, 3, 4
}
The Async Trick ?
Async functions let you run code without blocking the main thread, but they can be tricky in loops.
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i); // Prints 3, 3, 3 — unexpected!
}, 1000);
}
Why? setTimeout is async. By the time it runs, the loop has finished, and i is 3.
The Fix ???
Use let to fix the scope issue:
领英推荐
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i); // Prints 0, 1, 2
}, 1000);
}
forEach Trap ???
forEach doesn’t wait for async functions, leading to chaotic results:
[0, 1, 2].forEach(async (i) => {
await new Promise(resolve => setTimeout(() => {
console.log(i);
resolve();
}, 1000));
});
The Better Option ??
Use for...of for async/await in loops:
async function loopWithAsync() {
for (let i of [0, 1, 2]) {
await new Promise(resolve => setTimeout(() => {
console.log(i);
resolve();
}, 1000));
}
}
loopWithAsync(); // Prints 0, 1, 2 with a 1-second delay
TL;DR:
JavaScript loops with async? A thrilling ride if you know the tricks! ??
#JavaScript #Async #CodingTips #WebDevelopment #TechFun