Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with many asynchronous operations where callback statements can generate callback-hell resulting in unmanageable code.
Before the Promise event, callback functions were used a lot, but they had limited functionality and produced unmanageable code. Multiple nested callback functions create callback hell that leads to unmanageable code. Events do not handle asynchronous activities well.
1 2 3 4 5 6 7 8 | firstFunction(args, function() { secondFunction(args, function() { thirdFunction(args, function() { // And so on… }); }); }); |
Promise is the ideal choice for the simplest handling of asynchronous operations. They can handle many asynchronous operations with ease and provide better error handling capabilities for function callbacks and events .
- Promises’ benefits:
- Help the callback function become more obvious
- Good handling of asynchronous activities
- Better definition of processing threads in asynchronous operations
- Error handling is better
- Promises status:
- fulfilled : processing involved when the promise was successful
- rejected : The handle involved when the promise has failed
- pending : The pending Promise, ie no fulfilled or rejected
- settled : Promise was fulfilled or rejected
- A Promise can be created by using the Promise constructor1234var promise = new Promise(function(resolve, reject){//do something});
- Parameters
- The Promise constructor takes only one argument as a callback function.
- The callback function accepts two arguments, resolve and reject.
- Do things inside the callback function, and if everything goes well, call resolve.
- If the desired operation fails, call reject.
Here is an example:
123456789101112131415161718var promise = new Promise(function(resolve, reject) {const a = 'Okay';const b = 'Okay'if(a === b) {resolve();} else {reject();}});promise.then(function () {console.log('Success.');}).catch(function () {console.log('Failed.');});Output
12Success. - Promise is used like? Promises can be used using the .then and .catch methods.1.then ()
- then () is called when the promise returns to be resolved or rejected.Parameters:
The .then () method takes two functions as parameters.
- The first function is executed if the promise is resolved and gets the result.
- The second function is executed if the promise is rejected and received an error. (There is a better way to fix the error using the .catch () method)
About the syntax:
123456.then(function(result){//handle success}, function(error){//handle error})Promise Rejected Example:
123456789101112var promise = new Promise(function(resolve, reject) {resolve('Handle success.');})promise.then(function(successMessage) {//success handler function is invokedconsole.log(successMessage);}, function(errorMessage) {console.log(errorMessage);})Output
12Handle success.Promise Rejected Example:
123456789101112var promise = new Promise(function(resolve, reject) {reject('Handle error.');})promise.then(function(successMessage) {console.log(successMessage);}, function(errorMessage) {//error handler function is invokedconsole.log(errorMessage);})Output
12Handle error.
2. catch ()
- catch () is called when the promise rejects or an error occurs on execution.Parameters:
catch () takes a function as an argument. It’s the error handling function or a reject promise.
Execution syntax:
1234.catch(function(error) {// Handler error})Promise Rejected Example
123456789101112var promise = new Promise(function(resolve, reject) {reject('Promise Rejected.');})promise.then(function(successMessage) {console.log(successMessage);}, function(errorMessage) {//error handler function is invokedconsole.log(errorMessage);})Output
12Promise Rejected.Or is:
123456789101112var promise = new Promise(function(resolve, reject) {throw new Error('Some error has occured.')})promise.then(function(successMessage) {console.log(successMessage);}, function(errorMessage) {//error handler function is invokedconsole.log(errorMessage);})Output
12Some error has occured.
- then () is called when the promise returns to be resolved or rejected.Parameters:
So how is Promise applied?
- That’s when you want to handle asynchronous events.
- It’s a good solution to avoid callback hell .