What are Promises in JS?
To manage asynchronous actions in JavaScript, promises are used. It is an assurance that something will be done. The promise is used to keep track of whether the asynchronous event has been executed or not and determines what happens after the event has occurred.
A Promise has four states:
- fulfilled: Action related to the promise succeeded
- rejected: Action related to the promise failed
- pending: Promise is still pending i.e. not fulfilled or rejected yet
- settled: Promise has fulfilled or rejected
Syntax:
Let promise = new Promise(function(resolve, reject){
// do something
});
A promise can be created using Promise constructor.
Parameters:
- Promise constructor takes only one argument which is a callback function (and that callback function is also referred as an anonymous function too).
- Callback function takes two arguments, resolve and reject
- Perform operations inside the callback function and if everything went well then call resolve.
- If desired operations do not go well then call reject.
Example: In this example, a Promise is created to compare two strings, ‘w3wiki’ and ‘w3wiki’. If the strings match, the promise resolves, logging a success message. Otherwise, it rejects, logging an error message. The then
method handles success, and the catch
method handles errors.
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' ); }); |
Success, You are a GEEK
Benefits of Promises:
- Improves Code Readability
- Better handling of asynchronous operations
- Better flow of control definition in asynchronous logic
- Better Error Handling