What is Promise in JavaScript (ES)
February 13, 2020
What is Promise in JavaScript
A promise in Javascript is an object which represent the eventual completion or failure of an asynchronous operation. Promises represent a proxy for a value which are getting in some point in the future.
A promise can have 3 states which are the following:
- Pending: This is the initial state of the promise, the promise is now waiting for either to be resolved or rejected. For example, when are reaching out to the web with an AJAX request and wrapping the request in a promise. Then the promise will be pending in the time window in which the request is not returned.
- Fulfilled:When the operation is completed successfully, the promise is fulfilled. For example, when we are reaching out to be web using AJAX for some JSON data and wrapping it in a promise. When we are successfully getting data back the promise is said to be fulfilled.
-
Rejected:When the operation has failed, the promise is rejected. For example, when we are reaching out to be web using AJAX for some JSON data and wrapping it in a promise. When we are getting a 404 error the promise has been rejected.
Promise Constructor:
We can create a promise in the following manner:
let BitFrit = new Promise((res, rej) => { console.log('synchronously executed'); if (Math.random() > 0.5) { res('Success'); } else { rej('Error'); } }) BitFrit.then((val) => { console.log('asynchronously executed: ' + val); }).catch((err) => { console.log('asynchronously executed: ' + err); }).finally(() => { console.log('promise done executing'); });