Async/Await in JavaScript
async
and await
are modern JavaScript features that simplify working with asynchronous code, making it easier to read and maintain. They are built on top of Promises but allow you to write asynchronous code that looks more like synchronous code.
1️⃣ async
Function
The async
keyword is used to declare an asynchronous function. A async
function always returns a Promise, even if you return a non-Promise value. If the function returns a value, the Promise
is resolved with that value. If an error is thrown, the request Promise
is rejected.
In this case, the example()
function returns a resolved Promise with the value "Hello, world!"
. You can use .then()
to handle the Promise.
2️⃣ await
Expression
The await
keyword can only be used inside a async
function. It pauses the execution of the function until the Promise
is resolved or rejected, and then it returns the result.
- If the Promise resolves,
await
returns the resolved value. - If the Promise is rejected, an error is thrown.
In this example:
fetch()
returns aPromise
that resolves to the response object.await
pauses the function untilfetch()
resolves, and then it proceeds to call.json()
on the result.
3️⃣ Handling Errors with try...catch
When using await
, you can use try...catch
blocks to handle errors gracefully. This is similar to handling errors with synchronous code.
In this example:
- If the
fetch()
request fails or the.json()
method throws an error, thecatch
block will handle the error.
4️⃣ Multiple await
Calls
You can use multiple await
expressions inside an async
function to handle multiple asynchronous operations sequentially.
This will wait for the first fetch()
to resolve, then move on to the second one. If you need to make them in parallel, you can use Promise.all()
.
5️⃣ Parallel Execution with Promise.all()
If you have multiple asynchronous tasks that can run in parallel, you can use Promise.all()
to execute them concurrently and wait for all of them to finish.
In this case:
Promise.all()
waits for bothfetch()
requests to resolve before proceeding.- It executes both requests concurrently, reducing the total wait time compared to sequential execution.
6️⃣ Example: Using async/await
with User Input
Here’s a practical example where you fetch data based on user input asynchronously:
This function:
- Takes an
userId
as input. - Fetches the user data asynchronously.
- Handles any errors that occur during the fetch operation.
7️⃣ async/await
with Loops
You can use async/await
in loops to handle asynchronous operations one by one. Here's an example where we fetch multiple user profiles:
However, if you want to make multiple requests concurrently (in parallel), you can use Promise.all()
as shown earlier.
8️⃣ Benefits of async/await
- Simplicity: Writing asynchronous code looks more like synchronous code, making it easier to read and maintain.
- Error Handling: You can use
try...catch
to handle errors in a more synchronous and structured way. - Debugging: Debugging async code is simpler, as stack traces are more meaningful.
- Cleaner Code: It avoids the "callback hell" or nested
then()
methods that come with using raw Promises.
9️⃣ Important Points
-
async
Functions Always Return a Promise: Even if you return a non-Promise value, it will be automatically wrapped in a resolved Promise. -
await
Can Only Be Used Insideasync
Functions: Usingawait
outside anasync
function will result in an error.
Conclusion
async
and await
make asynchronous programming in JavaScript more intuitive by eliminating the need for chaining then()
or dealing with callbacks. They allow you to write cleaner, more readable code that behaves asynchronously but looks synchronous. By using async/await
, you simplify error handling, enhance readability, and create efficient and easy-to-debug code.
Let me know if you have any more questions or need further examples! 😊