Promises In JS
Promises in JavaScript When JavaScript performs an operation that takes some time, such as fetching data from a server, it does not want to wait and block the rest of the program. Instead, JavaScript can handle the operation asynchronously. A Promise is an object that represents the eventual result of an asynchronous operation. In simple words, a Promise means "I don't have the result right now, but I will give you the result later." Creating a Promise We can create a Promise using the built-in Promise constructor: const result = new Promise (( resolve , reject ) => { const age = 10 ; setTimeout (() => { if ( age >= 18 ) { resolve ( " You are eligible to vote " ); } else { reject ( " You are not eligible to vote " ); } }, 3000 ); }); Here, Promise is a built-in JavaScript constructor, and new Promise() creates a new Promise object. The function passed to new Promise() is called the executor function : ( resolve , reject ) => { // code } resolve and reject are parameters of this executor function. The Promise constructor provides functions as arguments for these parameters. We call resolve() when the operation is successful and reject() when the operation fails. resolve ( " You are eligible to vote " ); means the operation was successful. reject ( " You are not eligible to vote " ); means the operation failed. Promise States A Promise has three possible states: State Meaning Pending The operation is still in progress Fulfilled The operation completed successfully Rejected The operation failed In our example, when the Promise is created, it is initially pending . After 3 seconds, the age is checked. Since the age is 10 , the condition is false and reject() is called. So the Promise changes from: Pending ↓ Rejected If the age were 18 or above, resolve() would be called instead: Pending ↓ Fulfilled Handling a Promise After creating the Promise, we can use .then() to handle a successful result and .catch() to handle an error. const result = new Promise (( resolve , rejec