What are promises in JavaScript ?
Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.
A Promise
is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
A Promise
is in one of these states:
- pending: initial state, neither fulfilled nor rejected.
- fulfilled: meaning that the operation was completed successfully.
- rejected: meaning that the operation failed.
Why do we need Promises?
JavaScript is a single-threaded language because while running code on a single thread, it can be really easy to implement as we don't have to deal with the complicated scenarios that arise in the multi-threaded environment like deadlock. Since JavaScript is a single-threaded language, it is synchronous in nature.
Syntax-
var promise = new Promise(function(resolve, reject){
//do something
});
Promise Example-
Examples: Promise Rejected-
var promise = new Promise(function(resolve, reject) {
reject('Promise Rejected')
})
promise
.then(function(successMessage) {
console.log(successMessage);
})
.catch(function(errorMessage) {
//error handler function is invoked
console.log(errorMessage);
});
Promises Applications In java script-
- Promises are used for asynchronous handling of events.
- Promises are used to handle asynchronous http requests
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Comments
Post a Comment