JS Tutorial



JS PROMISES


JavaScript Promises πŸ’‘

A Promise in JavaScript represents a value that may be available now, or in the future, or never. Promises are used to handle asynchronous operations like reading files, making HTTP requests, etc. It allows you to attach callbacks to handle success or failure.

πŸ”„ Promise States

A promise can be in one of three states:

  • Pending: The initial state, before the promise is fulfilled or rejected.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

βš™οΈ Creating a Promise

To create a promise, use the new Promise() constructor. Here's how it works:

// Creating a new Promise
let myPromise = new Promise(function(resolve, reject) {
  let success = true;

  if (success) {
    resolve("The operation was successful!");
  } else {
    reject("The operation failed.");
  }
});

myPromise.then(function(result) {
  console.log(result);  // "The operation was successful!"
}).catch(function(error) {
  console.log(error);   // "The operation failed."
});
  

πŸ“Œ Chaining Promises

Promises can be chained together. Each then() method returns a new promise, allowing multiple actions to occur in sequence.

let promiseChain = new Promise(function(resolve, reject) {
  resolve(10);
});

promiseChain.then(function(result) {
  console.log(result);  // 10
  return result * 2;    // Returning a new value for the next .then()
}).then(function(result) {
  console.log(result);  // 20
}).catch(function(error) {
  console.log(error);
});
  

πŸ”„ Live Example: Simulate a Delay with Promises

Result will be shown here after operation completes.

πŸ“Œ Promise.all() and Promise.race()

In some cases, you may want to wait for multiple promises to resolve or race against them. JavaScript provides two handy methods:

  • Promise.all(): Waits for all promises to resolve or rejects if any promise fails.
  • Promise.race(): Resolves or rejects as soon as one of the promises resolves or rejects.
let promise1 = new Promise(function(resolve) {
  setTimeout(resolve, 1000, "One");
});

let promise2 = new Promise(function(resolve) {
  setTimeout(resolve, 500, "Two");
});

Promise.all([promise1, promise2]).then(function(values) {
  console.log(values);  // ["One", "Two"]
});

Promise.race([promise1, promise2]).then(function(value) {
  console.log(value);  // "Two" (The first to resolve)
});
  

⚑ Handling Multiple Async Operations with Promises

Promises are ideal for handling multiple asynchronous operations. Here’s an example where you perform multiple async operations and use Promise.all() to wait for all of them to complete:

function fetchData(url) {
  return new Promise(function(resolve) {
    setTimeout(function() {
      resolve(`Data fetched from ${url}`);
    }, 1000);
  });
}

let api1 = fetchData("https://api1.com");
let api2 = fetchData("https://api2.com");

Promise.all([api1, api2]).then(function(results) {
  console.log(results);  // ["Data fetched from https://api1.com", "Data fetched from https://api2.com"]
});
  

⚠️ Error Handling in Promises

You can handle errors in promises using the catch() method, which catches any rejected promise or error thrown:

let errorPromise = new Promise(function(resolve, reject) {
  reject("Something went wrong!");
});

errorPromise.catch(function(error) {
  console.log(error);  // "Something went wrong!"
});
  
Note: Promises provide a cleaner and more manageable way to handle asynchronous operations than using callbacks, especially when dealing with multiple async tasks.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review