Asynchronous Programming in JavaScript

·

2 min read

  1. Introduction to Asynchronous Programming

    • JavaScript runs synchronously by default (executes code instantly).

    • Example: Changing a variable and logging it happens instantly.

    • However, tasks like fetching data from an API take time and are not instant.

  2. Promises

    • Promises are used to handle asynchronous operations in JavaScript.

    • A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation.

    • Structure of a Promise:

        let event = new Promise((resolve, reject) => {
          if (condition) {
            resolve(value); // Success
          } else {
            reject(error); // Failure
          }
        });
      
    • Resolve: Called when the operation is successful.

    • Reject: Called when the operation fails.

    • Handling Promises:

      • .then(): Handles the resolved value.

      • .catch(): Handles errors (rejected state).

      • .finally(): Executes regardless of success or failure.

    • Example:

        event
          .then((name) => console.log(name)) // Success
          .catch((error) => console.log(error)) // Error
          .finally(() => console.log("Promise finished")); // Always runs
      
  3. Fetching Data with Promises

    • Example: Fetching data from an API using axios (a library for making HTTP requests).

    • API requests return a Promise, which must be resolved to access the data.

    • Example:

        axios.get('https://api.example.com/data')
          .then((res) => console.log(res.data)) // Success
          .catch((error) => console.log(error)) // Error
          .finally(() => console.log("Promise resolved")); // Always runs
      
  4. Async/Await

    • Async/Await is syntactic sugar for Promises, making asynchronous code look cleaner and more readable.

    • Async: Declares a function as asynchronous.

    • Await: Pauses the execution of the function until the Promise is resolved.

    • Example:

        async function fetchData() {
          try {
            const res = await axios.get('https://api.example.com/data');
            console.log(res.data); // Success
          } catch (error) {
            console.log(error); // Error
          } finally {
            console.log("Request completed"); // Always runs
          }
        }
        fetchData();
      
    • Error Handling: Use try-catch blocks to handle errors in async/await.

  5. Comparison: Promises vs Async/Await

    • Promises: Use .then(), .catch(), and .finally() for handling asynchronous operations.

    • Async/Await: Makes code cleaner and avoids callback hell.

    • Both achieve the same result, but async/await is often preferred for readability.

  6. Practical Example

    • Fetching data from a cat facts API:

      • Using Promises:

          axios.get('https://catfact.ninja/facts')
            .then((res) => console.log(res.data))
            .catch((error) => console.log(error));
        
      • Using Async/Await:

          async function fetchCatFacts() {
            try {
              const res = await axios.get('https://catfact.ninja/facts');
              console.log(res.data);
            } catch (error) {
              console.log(error);
            }
          }
          fetchCatFacts();
        
  7. Key Takeaways

    • Promises and async/await are essential for handling asynchronous operations in JavaScript.

    • Promises are more explicit, while async/await offers cleaner syntax.

    • Use .then(), .catch(), and .finally() with Promises.

    • Use try-catch blocks with async/await for error handling.


Conclusion

  • Asynchronous programming is crucial for tasks like API