Saturday, November 9, 2024

JavaScript fetch API dissected, Promise Chaining

The fetch function returns a promise object, which may be in pending, fulfilled, or rejected state. Initially, the promise is pending. When the promise is fulfilled, the callback function passed to then() is executed; if rejected, the callback function passed to catch() is executed. Each then() and catch() returns a new promise, allowing for chaining. Although it's usually cleaner to chain promises sequentially, then() and catch() can contain additional nested callbacks if needed for more complex logic.
The then() and catch() are not callback functions themselves—they are methods provided by the Promise object. These methods take callback functions as arguments, which are then executed when the promise is fulfilled or rejected.

Here's a clearer breakdown of above statements:

1. then() and catch() as Methods:
   - then() and catch() are methods that allow you to attach handlers (callbacks) to a promise.
   - When you call promise.then(...) or promise.catch(...), you're calling a method that accepts a function (callback) as an argument.

2. Callbacks Passed to then() and catch():
   - The actual functions you pass into then() and catch() are the callback functions. For example:   
 fetch('https://api.example.com/data')
       .then(response => console.log(response))  // This response => console.log(response) is a callback function.
       .catch(error => console.error(error));    // This error => console.error(error) is also a callback function.   
3. Behavior of then() and catch():
   - The then() method is designed to handle the resolved value of a promise and automatically returns a new promise.
   - Similarly, catch() handles any error or rejection in the promise chain and also returns a new promise, allowing further chaining.

Summary

- then() and catch() are methods on a promise, not callbacks.
- The functions passed to then() and catch() are callbacks that are executed based on the promise’s outcome (fulfilled or rejected).

Primise Chaining

The fetch, then and catch functions return a promise so they can be chained. The fetch(), then(), and catch() functions each return a promise, which is what makes chaining possible in JavaScript.

Here’s a more detailed look at how this works:

fetch() Returns a Promise:
  • The fetch() function initiates a network request and returns a promise that resolves to the Response object if the request is successful, or rejects if there’s a network error.
  • This initial promise can be chained by calling then() to handle the response, making it easy to perform further actions on the response data.

then() Returns a New Promise:
  • When you call then() on a promise, it processes the result of the previous promise and returns a new promise.
  • This new promise represents the completion of the callback function passed to then(), allowing you to chain additional operations.
  • This means you can keep calling then() on each returned promise, forming a promise chain.

catch() Returns a New Promise:
  • Similarly, the catch() method handles errors that occur in the promise chain and also returns a new promise.
  • This allows you to continue chaining even after handling an error.
Here’s an example to illustrate:

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) throw new Error('Network response was not ok');
    return response.json();
  })
  .then(data => {
    console.log('Data received:', data);
    return fetch('https://api.example.com/another-endpoint'); // This returns another promise
  })
  .then(secondResponse => secondResponse.json())
  .then(secondData => {
    console.log('Second data received:', secondData);
  })
  .catch(error => {
    console.error('Fetch error:', error);
  });
Summary
  • fetch(), then(), and catch() return promises, which makes chaining them possible.
  • This chaining allows for handling multiple asynchronous steps in sequence, with then() processing successful results and catch() handling any errors that arise.

No comments:

Post a Comment

Hot Topics