Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Promises and Fetch API

Promises and Fetch API

Promises and the Fetch API are two powerful features in JavaScript that make working with asynchronous operations, such as network requests, much more convenient and readable. Let's explore each of them:

Promises:

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It allows you to handle asynchronous code in a more synchronous, readable manner.

let promise = new Promise((resolve, reject) => {
  // Asynchronous operation
  let success = true;
  if (success) {
    resolve('Operation successful'); // Resolve when successful
  } else {
    reject('Operation failed'); // Reject on error
  }
});

promise
  .then(result => {
    console.log(result); // Called when promise is resolved
  })
  .catch(error => {
    console.error(error); // Called when promise is rejected
  });
 

Fetch API:

The Fetch API provides an easy way to make HTTP requests and handle responses.

Making a GET Request:

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json(); // Parse response as JSON
  })
  .then(data => {
    console.log(data); // Process JSON data
  })
  .catch(error => {
    console.error('Error:', error);
  });
 

Making a POST Request:

fetch('https://api.example.com/submit', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: 'John Doe', email: 'john@example.com' })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
 

Handling Errors:

The catch method of a Promise is used to handle any errors that may occur during the asynchronous operation.

Chaining Promises:

You can chain multiple .then() calls to perform a series of asynchronous operations in sequence.

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    return fetch('https://api.example.com/otherData'); // Return a new promise
  })
  .then(response => response.json())
  .then(otherData => {
    console.log(otherData);
  })
  .catch(error => {
    console.error('Error:', error);
  });
 

Combining Promises:

You can use Promise.all() to combine multiple promises and wait for all of them to resolve.

let promise1 = fetch('https://api.example.com/data1');
let promise2 = fetch('https://api.example.com/data2');

Promise.all([promise1, promise2])
  .then(responses => Promise.all(responses.map(response => response.json())))
  .then(dataArray => {
    console.log(dataArray[0], dataArray[1]);
  })
  .catch(error => console.error('Error:', error));