Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save KeyurRamoliya/313e7a8ae939c0aa2bae6c09460396b4 to your computer and use it in GitHub Desktop.
Save KeyurRamoliya/313e7a8ae939c0aa2bae6c09460396b4 to your computer and use it in GitHub Desktop.
Using Promises for Asynchronous Operations

Using Promises for Asynchronous Operations

JavaScript is often used for tasks that involve asynchronous operations, like fetching data from an API. Promises are a fundamental concept for handling asynchronous code and managing the flow of execution.

A Promise represents a value that may not be available yet but will be at some point in the future, or it may fail. Promises provide a clean and structured way to handle asynchronous operations.

Below is a basic example of using Promises for an asynchronous operation, such as fetching data from an API using fetch.

A few key points about Promises:

  • States: Promises have three states: pending (initial state), fulfilled (resolved with a value), and rejected (failed with a reason).
  • .then() and .catch(): You can chain .then() to handle successful resolution and .catch() to handle any errors or rejections. Chaining allows for a more structured way to handle asynchronous code.
  • Async/Await: ES6 introduced async/await, which provides a more readable and synchronous-like way to work with Promises. You can use async functions with await to pause execution until the Promise is resolved or rejected.
// Creating a Promise for fetching data
const fetchData = () => {
  return fetch('https://api.ipify.org/?format=json')
    .then((response) => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .catch((error) => {
      console.error('Error fetching data:', error);
    });
};

// Using the Promise
fetchData()
  .then((data) => {
    console.log('Data fetched successfully:', data);
  })
  .catch((error) => {
    console.error('Error occurred:', error);
  });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment