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
Master of Business Administration (90 ECTS)Master in International Management (120 ECTS)Bachelor of Business Administration (180 ECTS)B.Sc. Computer Science (180 ECTS)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 MediaMS in Project ManagementMSc 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 Digital MarketingMSc in Sustainable Luxury and Creative IndustriesMSc in Sustainable Global Supply Chain ManagementMSc in International Corporate FinanceMSc 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 AdministrationBachelors in International ManagementMS Computer Science with Artificial Intelligence and Machine Learning ConcentrationMaster of Business AdministrationMaster of Business AdministrationMSc in International FinanceMSc in International Management and Global LeadershipMaster of Business AdministrationBachelor of Business
For College Students

Promises as Solution to Callback Hell in Javascript

$$/$$

Can you recall the code you saw in the segment on Callback Hell? Given below is that code:

 

Code Snippet *:

// CALLBACK HELL
// function to fetch details of user in Student Management System
const fetchUserDetails = (username, password, callback) => {
    database.authenticateUser(username, password, (error, userInfo) => {
        if (error) {
            callback(error);
        } else {
            database.getRoles(userInfo, (error, rolesInfo) => {
                if (error) {
                    callback(error);
                } else {
                    database.getPermissions(rolesInfo, (error, permissionsInfo) => {
                        if (error) {
                            callback(error);
                        } else {
                            callback(null, userInfo, rolesInfo, permissionsInfo);
                        }
                    });
                }
            });
        }
    });
}

const callback = (error, userInfo, rolesInfo, permissionsInfo) => {
    // some code here
}

 

*Note that the above code will not run as it is because there is no database object yet on which you can invoke the specified methods. It is just an overview of how a small application can be defined.

 

Do you remember that you were told that promises actually solve the problem of the callback hell? How? Well, you’ll learn that in the next video with Srishti.

$$/$$

Following is the code which you looked at in the last video when dealing with the problem of callback hell using promises:

 

Code Snippet:

// USING PROMISES
// function to fetch details of user in Student Management System
const fetchUserDetails = (username, password) => {
    database.authenticateUser(username, password)
        .then(userInfo => dataBase.getRoles(userInfo))
        .then(rolesInfo => dataBase.getPermissions(rolesInfo))
        .then(permissionsInfo => {
            // code written inside the function named 'callback'
        })
        .catch((err) => {
            // code to handle error
        });
};

 

Clearly, following are the advantages of using promises:

  • Improved code readability
  • Better error handling
  • Neater way of defining flow of logic control
  • Reducing inter-dependency of code (coupling)

 

In the section of callbacks, you looked at another example of callback hell with Sakshi. Let us look at that example too and see how promises solve the problem of callback hell.

$$/$$

In the last video, you looked at the solution to solve the problem with callback hell. Modify the example taken in the video to add 'getContinents' in the chain gives the following code snippet:

 

Code Snippet:

const getAddress = () => {
 getContinents.then(continent => {
   return getCountries(continent);
 }, error => {
   console.log(new Error(error));
 }).then(country => {
   return getStates(country);
 }, error => {
   console.log(new Error(error));
 }).then(state => {
   return getCities(state);
 }, error => {
   console.log(new Error(error));
 }).then(() => {
   return done();
 }, error => {
   console.log(new Error(error));
 });
}

const getContinents = new Promise((resolve, reject) => {
 setTimeout(() => {
   // code to get all continents
   let continent = "Asia";
   console.log(continent);
   resolve(continent);
 }, 1000);
});

const getCountries = (continent) => {
 return new Promise((resolve, reject) => {
   setTimeout(() => {
     // code to get all countries
     let country = "India";
     console.log(country);
     resolve(country);
   }, 1000);
 });
}

const getStates = (country) => {
 return new Promise((resolve, reject) => {
   setTimeout(() => {
     // code to get all states
     let state = "Rajasthan";
     console.log(state);
     resolve(state);
   }, 1000);
 });
}

const getCities = (state) => {
 return new Promise((resolve, reject) => {
   setTimeout(() => {
     // code to get all cities
     let city = "Jaipur";
     console.log(city);
     resolve();
   }, 1000);
 });
}

const done = () => {
 console.log("DONE!");
};

getAddress();

 

Output:

Asia
India
Rajasthan
Jaipur
DONE!

 

Alright, seems like promises are the best way to deal with asynchronous behaviour in JavaScript. Wait, there’s even a better solution than promises. You’ll look at it in the next segment.