Async/await

Async/await

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.

async function example() { return "Hello, world!"; } example().then(result => { console.log(result); // "Hello, world!" });

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.
async function getData() { const result = await fetch('https://api.example.com/data'); const data = await result.json(); console.log(data); }

In this example:

  • fetch() returns a Promise that resolves to the response object.
  • await pauses the function until fetch() 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.

async function fetchData() { try { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } }

In this example:

  • If the fetch() request fails or the .json() method throws an error, the catch 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.

async function getMultipleData() { const response1 = await fetch('https://api.example.com/data1'); const data1 = await response1.json(); console.log(data1); const response2 = await fetch('https://api.example.com/data2'); const data2 = await response2.json(); console.log(data2); }

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.

async function getMultipleDataInParallel() { const [response1, response2] = await Promise.all([ fetch('https://api.example.com/data1'), fetch('https://api.example.com/data2') ]); const data1 = await response1.json(); const data2 = await response2.json(); console.log(data1); console.log(data2); }

In this case:

  • Promise.all() waits for both fetch() 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:

async function getUserData(userId) { try { const response = await fetch(`https://api.example.com/users/${userId}`); const userData = await response.json(); console.log(userData); } catch (error) { console.error('Failed to fetch user data:', error); } } const userId = 1; getUserData(userId);

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:

async function getUsers(userIds) { const users = []; for (let id of userIds) { const response = await fetch(`https://api.example.com/users/${id}`); const user = await response.json(); users.push(user); } return users; } const userIds = [1, 2, 3]; getUsers(userIds).then(users => console.log(users));

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.

    async function foo() { return 42; // Returns Promise.resolve(42) }
  • await Can Only Be Used Inside async Functions: Using await outside an async function will result in an error.

    // Incorrect usage const data = await fetch('https://api.example.com'); // SyntaxError: await is only valid in async functions

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! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close