How to create and use JavaScript promises for asynchronous programming?

To create and use JavaScript promises for asynchronous programming, follow these steps:

  1. Create a new Promise: Use the Promise constructor to create a new Promise object. The constructor takes a function as an argument, with two parameters: resolve and reject. These parameters are functions that you call to either fulfill or reject the Promise. Inside this function, you write the asynchronous code that you want to wrap in a Promise.
const myPromise = new Promise((resolve, reject) => { // Asynchronous code here });
  1. Resolve or reject the Promise: Inside the Promise function, use the resolve function to fulfill the Promise, or the reject function to reject the Promise. Pass the desired result or error as an argument to these functions.
const myPromise = new Promise((resolve, reject) => { setTimeout(() => { const randomNum = Math.random(); if (randomNum > 0.5) { resolve(randomNum); } else { reject(new Error('Random number is less than 0.5')); } }, 1000); });
  1. Handle the Promise's result or error: Use the then method to handle the resolved Promise, and the catch method to handle the rejected Promise. These methods take a function as an argument, which will be called when the Promise is fulfilled or rejected.
myPromise .then(result => { console.log('Promise fulfilled:', result); }) .catch(error => { console.error('Promise rejected:', error); });
  1. Chaining Promises: You can chain multiple Promises together using the then method. This allows you to execute multiple asynchronous operations in sequence.
myPromise .then(result => { console.log('Promise fulfilled:', result); return anotherPromise(result); }) .then(anotherResult => { console.log('Another Promise fulfilled:', anotherResult); }) .catch(error => { console.error('Promise rejected:', error); });

That's it! You have created and used a JavaScript Promise for asynchronous programming. Promises provide a more elegant way to handle asynchronous operations and avoid callback hell.