What is the use of Promises in JavaScript ?
Promises in JavaScript are a way to handle asynchronous operations. They have three states: pending, fulfilled, and rejected. You create a promise using the Promise
constructor, and it resolves with a value or rejects with an error. Promises are consumed .then()
for success and .catch()
for errors. They support chaining for sequential operations and can be simplified with async/await
a more synchronous-like syntax. Promises improve code readability and help avoid callback hell.
Syntax:
let promise = new Promise(function(resolve, reject){
//do something
});
Example: This example shows how to create a basic promise object.
Javascript
let promise = new Promise( function (resolve, reject) { const x = "w3wiki" ; const y = "w3wiki" if (x === y) { resolve(); } else { reject(); } }); promise. then( function () { console.log( 'Success, You are a GEEK' ); }). catch ( function () { console.log( 'Some error has occurred' ); }); |
Output
Success, You are a GEEK
Contact Us