Tuesday, March 13, 2018

Manage synchronous functions without using any promise API or module in nodejs

In nodejs / javascript, we can use any promise api or nodejs modules.

here we will discuss how to manage all synchronous functions or process by our own without using any API or modules.

right now I will use Mongoose and MongoDB for fetching data from the database, but you can use any database or any data modeling tools which are used in your project.

Ex: Demo

var express = require('express'),
    router = express.Router(),
    User = require('../models/user'),
    UserProfile = require('../models/userProfile'),
    UserProfileAddress = require('../models/userProfileAddress');

/**
 * Manage synchronous functions without using any promise api or module
 */
router
    .route("/api/getUserInformation")
    .get(
        function (req, res) {

        var data ={}; //Store all information in data variable
        var userProcess = 0; // for determine is user process completed or not
        var profileProcess = 0; // for determine is user profile process completed  or not
        var profileAddressProcess = 0; // for determine is user profile address process completed  or not

        User.find({},function(err, userData){
            if(err){
                data.userData =[];
            }else{
                data.userData =userData;
            }
            userProcess = 1;
            finalProcess();
        });

        UserProfile.find({},function(err, userProfileData){
            if(err){
                data.userProfileData =[];
            }else{
                data.userProfileData =userProfileData;
            }
            profileProcess = 1;
            finalProcess();
        });

        UserProfileAddress.find({},function(err, userProfileAddressData){
            if(err){
                data.userProfileAddressData =[];
            }else{
                data.userProfileAddressData =userProfileAddressData;
            }
            profileAddressProcess = 1;
            finalProcess();
        });

        var finalProcess = function () {
            if (userProcess === 1 && profileProcess === 1 && profileAddressProcess === 1) {
                console.log(data);
            }
        };
       
        });

 module.exports = router;

In the above simple demo, finalProcess function will call as soon as any process will be completed,
but data will display only when all process will be completed.

Like as above demo we can create or manage our own promise/callback functions in nodejs.

By using this we can get the benefit of the synchronous process without none blocking any process.

Here, all user, userProfile, and UserProfileAddress will execute simultaneously and get all data after all process completed.

No comments:

Post a Comment