async/await without the pitfalls Async/await is the bread and butter of modern JavaScript.
It makes asynchronous code look synchronous, which is great for readability.
But it comes with its own set of footguns that can bite you in production.
Here's how to avoid them.
Pitfall 1: Forgetting in a loop You might write something like this, expecting each request to finish before the next starts: That's actually correct.
The issue arises when you forget inside a or : functions always return a promise.
So if you use with an async callback, you get an array of promises.
To fix it, use : But beware: fails fast.
If one request fails, the whole thing rejects.
If you need to handle failures individually, use instead.
Pitfall 2: Swallowing errors silently A common mistake is to catch an error and do nothing, which makes debugging a nightmare: Always at least log the error.
Even better, handle it gracefully or rethrow it: If you're using , unhandled promise rejections can crash your app in Node.js.
Always have a catch or a global handler.
Pitfall 3: Sequential execution when you need parallel Using inside a loop makes requests run one after another.
If they're independent, that's a performance hit: But don't go overboard.
Parallel requests can overwhelm a server or hit rate limits.
A good middle ground is to batch them with in chunks.
Pitfall 4: Using when you don't need it If a function doesn't have inside, making it is unnecessary and can cause subtle issues: It also changes error handling.
If you throw inside an async function, it becomes a rejected promise, not a synchronous exception.
Only use when you actually something.
Pitfall 5: Ignoring cancellation Async/await doesn't have built-in cancellation.
If you start a fetch and the user navigates away, you might still update the UI or leak resources.
A simple pattern is to use an : For more complex scenarios, libraries like exist, but sometimes a simple flag works: Pitfall 6: Forgetting that blocks the event loop doesn't block the event loop, but it does pause the function.
If you have a long-running synchronous operation inside an async function, it will block everything else.
For CPU-heavy tasks, use or worker threads to yield control.
Final tips Always use or on every promise you create.
Prefer when you need to handle partial failures.
Use for timeouts, but be careful about unhandled rejections from the losing promise.
Lint your code with rules that catch missing (like in ESLint).
Async/await is a powerful tool, but it's not magic.
Understand these pitfalls, and you'll write more robust asynchronous code.
Happy coding!