COURSES
MBAData Science & AnalyticsDoctorate Software & Tech AI | ML MarketingManagement
Professional Certificate Programme in HR Management and AnalyticsPost Graduate Certificate in Product ManagementExecutive Post Graduate Program in Healthcare ManagementExecutive PG Programme in Human Resource ManagementMBA in International Finance (integrated with ACCA, UK)Global Master Certificate in Integrated Supply Chain ManagementAdvanced General Management ProgramManagement EssentialsLeadership and Management in New Age BusinessProduct Management Online Certificate ProgramStrategic Human Resources Leadership Cornell Certificate ProgramHuman Resources Management Certificate Program for Indian ExecutivesGlobal Professional Certificate in Effective Leadership and ManagementCSM® Certification TrainingCSPO® Certification TrainingLeading SAFe® 5.1 Training (SAFe® Agilist Certification)SAFe® 5.1 POPM CertificationSAFe® 5.1 Scrum Master Certification (SSM)Implementing SAFe® 5.1 with SPC CertificationSAFe® 5 Release Train Engineer (RTE) CertificationPMP® Certification TrainingPRINCE2® Foundation and Practitioner Certification
Law
Job Linked
Bootcamps
Study Abroad
MS in Data AnalyticsMS in Project ManagementMS in Information TechnologyMasters Degree in Data Analytics and VisualizationMasters Degree in Artificial IntelligenceMBS in Entrepreneurship and MarketingMSc in Data AnalyticsMS in Data AnalyticsMS in Computer ScienceMaster of Science in Business AnalyticsMaster of Business Administration MS in Data ScienceMS in Information TechnologyMaster of Business AdministrationMS in Applied Data ScienceMaster of Business Administration | STEMMS in Data AnalyticsM.Sc. Data Science (60 ECTS)Master of Business AdministrationMS in Information Technology and Administrative Management MS in Computer Science Master of Business Administration MBA General Management-90 ECTSMSc International Business ManagementMS Data Science Master of Business Administration MSc Business Intelligence and Data ScienceMS Data Analytics MS in Management Information SystemsMSc International Business and ManagementMS Engineering ManagementMS in Machine Learning EngineeringMS in Engineering ManagementMSc Data EngineeringMSc Artificial Intelligence EngineeringMPS in InformaticsMPS in Applied Machine IntelligenceMS in Project ManagementMPS in AnalyticsMS in Project ManagementMS in Organizational LeadershipMPS in Analytics - NEU CanadaMBA with specializationMPS in Informatics - NEU Canada Master in Business AdministrationMS in Digital Marketing and MediaMSc Sustainable Tourism and Event ManagementMSc in Circular Economy and Sustainable InnovationMSc in Impact Finance and Fintech ManagementMS Computer ScienceMS in Applied StatisticsMaster in Computer Information SystemsMBA in Technology, Innovation and EntrepreneurshipMSc Data Science with Work PlacementMSc Global Business Management with Work Placement MBA with Work PlacementMS in Robotics and Autonomous SystemsMS in Civil EngineeringMS in Internet of ThingsMSc International Logistics and Supply Chain ManagementMBA- Business InformaticsMSc International ManagementMBA in Strategic Data Driven ManagementMSc Digital MarketingMBA Business and MarketingMaster of Business AdministrationMSc in Sustainable Global Supply Chain ManagementMSc Digital Business Analytics MSc in International HospitalityMSc Luxury and Innovation ManagementMaster of Business Administration-International Business ManagementMS in Computer EngineeringMS in Industrial and Systems EngineeringMSc International Business ManagementMaster in ManagementMSc MarketingMSc Business ManagementMSc Global Supply Chain ManagementMS in Information Systems and Technology with Business Intelligence and Analytics ConcentrationMSc Corporate FinanceMSc Data Analytics for BusinessMaster of Business AdministrationMaster of Business AdministrationMaster of Business AdministrationMSc in International FinanceMSc in International Management and Global LeadershipMaster of Business AdministrationBachelor of BusinessMaster of Business Administration 60 ECTSMaster of Business Administration 90 ECTSMaster of Business Administration 90 ECTSBachelor of Business AnalyticsBachelor of Information TechnologyMaster of Business AdministrationMBA Business AnalyticsMSc in Marketing Analytics and Data IntelligenceMS Biotechnology Management and EntrepreneurshipMSc in Luxury and Fashion ManagementMaster of Business Administration (90 ECTS)Bachelor of Business Administration (180 ECTS)B.Sc. Computer Science (180 ECTS) MSc in International Corporate Finance MSc in Sustainable Luxury and Creative IndustriesMSc Digital Marketing
For College Students

Javascript Promises – The promise.then, promise.catch and promise Explained

$$/$$

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()

  • invoked when the resolve() method is called and the promise is resolved
  • parameters of the successCallback hold the arguments passed into the resolve() callback

    For example, if you invoke the following callback method in the producer code:
    resolve(val);
    


    Then, the following method, which is the first argument of the then() method is invoked:

    successCallbackHandler(val)
    

     

2.       errorCallback()

  • invoked when the reject() method is called and the promise is rejected
  • parameters of the errorCallback hold the arguments passed into the reject() callback

    For example, if you invoke the following callback method in the producer code:
    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()

  • invoked when the reject() method is called and the promise is rejected
  • parameters of the errorCallbackHandler hold the arguments passed into the reject() callback
     

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.