Last updated on February 15, 2020
Part I – Getting Started JavaScript Promise
In continuation of the previous post on JavaScript Promise Quick Guide, here we have one more little to understand which seems to be the critical piece of writing JavaScript Promise Object.
I wish I would have known this uncovered piece of hidden caveat when I started writing with Plain JavaScript Promise for doing data manipulation code for asynchronous operation.
Usage
We have learnt from the previous post is that how to write JavaScript Promise natively, but here we will learn how to consume the created Promise function/Object and JavaScript Promise Error Handling.
In order to know how to consume the Promise Object, two Javascript keywords we should know. i.e., then & catch
The keyword then is for capturing success or resolved cases whereas catch
keyword is to handle error cases. Please check out the below code snippet to understand. The code here I use which is already given from the previous post.
const names =['Srinivasan','John'];
// Creating a Promise
function getUsers() {
return new Promise (function (resolve, reject) {
setTimeout(function (){
if(names && names.length) {
resolve(names);
} else {
reject ('No users...');
}
},2000);
});
};
// Consuming a Promise
function main() {
// calling a created promise function
const users = getUsers().then(function(data) {
// data manipulation
}).catch(function(error) {
// error handling
});
}
Error Handling
While writing JavaScript Promise error handling is the most important piece we should take care of.
When we think about error handling, the first thing will come to our mind is that try- catch
pattern which is super useful.
OH WHAT??? just sometime before we have learned to use catch
keyword for error handling case but this is different. Yes obviously, thus JavaScript Promise fundamentally differs in this case.
Quick tip, once this question was asked in my previous interview. When we will use try-catch
vs then-catch
pattern.
Typically, we can throw an error from Promise function with the help of throw
keyword.
// throwing an error
throw new Error('Your error message goes here...');
Once error thrown, Javascript promise is fundamentally designed in a way to get the thrown error in a catch block.
Eventually, catch block of try-catch
pattern will never trigger at all since the Promise function catch block will take care of those.