Last updated on February 13, 2020
This post will give you a solid foundation on JavaScript Promise but in a more concise way.
Part II – Hidden caveat of JavaScript Promise
Introduction
First things first, so what is Promise? A Promise is a JavaScript Object which helps to write an asynchronous function.
In other hand, the data will get resolved in an unpredictable time manner.
History of Promise
Knowing history of JavaScript promise is so essential as much as learning JavaScript Promise.
In earlier versions of JavaScript, Promise support was not there by default. In order to support we had a thrid party libraries such as bluebird, q.
Later starting from ES2015 Promise was supported natively (by default) hence this removed 3rd party library dependencies.
Concept of Promise
As said before, Promise is a JavaScript Object which we can write it as below,
Syntax,
new Promise(function(resolve,reject) {
// data retrieval code
});
Once we called the Promise, that triggers certain status of Promise during its life span of that call. The different status of Promise is,
- Promise.resolved
- Promise.rejected
- Promise.settled
- Promise.fulfilled
To give you an easy understanding, check out the below code snippet where I write asynchronous function with the help of Promise.
const names =['Srinivasan','John'];
const usersPromise = function getUsers() {
return new Promise (function (resolve, reject) {
setTimeout(function (){
if(names && names.length) {
resolve(names);
} else {
reject ('No users...');
}
},2000);
});
};
In the above code, I’ve done mimic the async operation with the help of JavaScript api setTimeout. resolve is for handling success case whereas reject is for throwing errors.
From the usersPromise variable we can derive it’s status. By using the status we can take the decision in order to perform an users action.
When Promise Object gets resolved or rejected, then Promise status is called as settled. If resolved, it would be fulfilled.
Missing Feature
One important thing to know that before using native JavaScript Promise is that we cannot cancel the triggered Promise.
This can be a caveat for this amazing JavaScript Promise Object. However, we’ve an another option to achieve this. Want to know more about that? Go on here.