Till now, you have learned all about the producer code, which produces some result. Now is the time to look at the consumer code, which consumes the result produced by the producer code. In the next video, you’ll learn more about consumers from Srishti.
In the last video, you learned that there are two types of consumer code:
1. then() method
2. catch() method
Watch the next video to learn more about then() method from Srishti.
In the last video, you learned the following syntax of the first consumer, which is the then() method:
Syntax of then() method:
// assume that the promise object named promiseObj already exists consisting of producer code
promiseObj.then(successCallback, errorCallback);
Simplifying the arguments (successCallback & errorCallback) as callbacks will reduce the above syntax to the one written below:
Syntax of then() method:
// writing the callbacks promiseObj.then((parametersToHoldArgumentsPassedWhenPromiseIsResolved) => { // code to execute when promise is resolved }, (parametersToHoldArgumentsPassedWhenPromiseIsRejected) => { // code to execute when promise is rejected });
Now, simplifying the parameters of the successCallback & errorCallback handlers will reduce the above syntax to the following:
Syntax of then() method:
promiseObj.then((value) => { // code for promise is resolved }, (error) => { // code for promise is rejected });
Note that in the above code, only one parameter named value is written in the successCallback and only one parameter named err is written in the errorCallback. However, you can have any number of parameters as you want and you can name them with any valid identifier because these just the callback methods and their syntax are similar to a normal method.
Following is the summary of what you learned till now in the above video:
The then() consumer has the following two arguments:
1. successCallback()
resolve(val);
Then, the following method, which is the first argument of the then() method is invoked:
successCallbackHandler(val)
2. errorCallback()
reject(err);
Then, the following method, which is the first argument of the then() method is invoked:
errorCallbackHandler(err)
You also looked at an example code utilizing the power of the then() consumer. Following is the code you looked at:
CASE A: When the promise is RESOLVED
// defining the promise object with the producer let promiseObj = new Promise((resolve, reject) => { console.log("Getting name from DB..."); setTimeout(() => { resolve("Srishti"); }, 3000); }); // defining the consumer promiseObj.then(val => { console.log(`Name received from DB = ${val}`); }, err => { console.log(`Error occurred = ${err}`); });
Output:
Getting name from DB..
Name received from DB = Srishti
CASE B: When the promise is REJECTED
// defining the promise object with the producer let promiseObj = new Promise((resolve, reject) => { console.log("Getting name from DB..."); setTimeout(() => { reject(new Error("Error getting name!")); }, 3000); }); // defining the consumer promiseObj.then(val => { console.log(`Name received from DB = ${val}`); }, err => { console.log(`Error occurred = ${err}`); });
Output:
Getting name from DB.. Error occurred = Error: Error getting name!
You also broke a common illusion that resolve and reject are keywords in JavaScript. The fact is that they are NOT keywords. You can use any valid identifier in place of resolve & reject. It is just for the sake of understanding that we use these names.
Also, a very important point to be noted is that the order of the resolve and reject callback methods must remain the same. The first parameter of the producer code is always treated as the resolve() callback method which represents that the code executed successfully and the second parameter of the producer code is always treated as the reject() callback method which represents that the code encountered some error while in execution. You cannot reverse their order.
In the next video, you’ll learn from Srishti about the next consumer, which is the catch() method.
In the last video, you learned the following syntax of the second consumer, which is the catch() method:
Syntax of catch() method:
// assume that the promise object named promiseObj already exists consisting promiseObj.catch(errorCallback);
Simplifying the argument (errorCallback) as a callback, will reduce the above syntax to the one written below:
Syntax of catch() method:
// writing the callback promiseObj.catch((parametersToHoldArgumentsPassedWhenPromiseIsRejected) => { // code to execute when promise is rejected });
Now, simplifying the parameters of the errorCallback handler will reduce the above syntax to the following:
Syntax of catch() method:
promiseObj.catch((err) => { // code to be executed when promise is rejected });
Note that in the above code, only one parameter named err is written in the errorCallback. However, you can have any number of parameters as you want and you can name them with any valid identifier because these are just the callback methods and their syntax is similar to a normal method.
Following is the summary of what you learned till now in the above video:
The catch() consumer has only one argument.
errorCallbackHandler()
For example, if you invoke the following callback method in the producer code:
reject(err);
Then, the following method, which is the argument of the catch() method is invoked:
errorCallbackHandler(err)
You also looked at an example code utilizing the power of the catch() consumer. Following is the code you looked at:
CASE: When the promise is REJECTED
// defining the promise object with the producer let promise = new Promise((resolve, reject) => { console.log("Getting name from DB..."); setTimeout(() => { reject(new Error("Could not get the name from DB!")); }, 3000); }); // defining the consumer promise.catch(err => { console.log(`Error occurred = ${err}`); });
Output:
Getting name from DB.. Error occurred = Error: Could not get the name from DB!
You learned that the catch() consumer method can be used to catch an error (if any) from the producer code and catch an error when the promise is rejected. But what would happen if there’s no error in the producer code or the resolve() callback method is invoked in the producer code? Will the control go inside the catch() method? Let’s check that out in the next video.
At timestamp ~1:15, after the promiseObj is defined, the instructor writes
console.log(promiseObj);
Now, when the output is checked, the status of the promise is still 'pending' and not 'resolved'. This is because the promise is getting resolved inside a setTimeout() method, which is an asynchronous method. As you are aware, the asynchronous methods are long-running tasks handled by the Web APIs, callback queue, event loop. Meanwhile, the remaining code is executed and the control comes back to the code written next, which is the log statement, thus logging the promiseObj to console. Since the promise is not yet resolved, the default status (pending) and the default value (undefined) of the promiseObj will be printed to the console.
In the last video, you learned the fact that the control will not go inside the catch() method if there is no error in the producer code or the promise is not rejected.