Javascript – Promise Chain Explained with Code Samples

This article represents tips and code samples on How to create and use a Promise Chain objects in Javascript. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos.
Promise Chain Explained with Code Samples

Following diagram represents the interaction between signup, Auth and User modules.

Promise Chain Example

Pay attention to some of the following in above diagram:

  • Signup module invokes login API on Auth service which returns a Promise object. The Signup completes the sync operation & watches for the Promise returned by Auth service to be resolved.
  • The Login API in turns invokes Get API on User object as a part of resolution. The Get API returns a Promise object.
  • Once the Get API is resolved, the User object is sent as part of “resolve” within Get API. This User object is in turn sent back to Signup module as part of “resolve” invoked within Auth Login API.

As per the above diagram, the details and code samples for three files are presented below:

  • signup.js: Invokes login API on Auth service.
    // Import the Auth module
    //
    var Auth = require('./Auth');
    
    // Create an Auth object
    //
    var auth = new Auth();
    //
    // Calls login API on Auth object
    // Returns a promise object
    //
    var loginPromise = auth.login({username:'ashukla', password:'pass123'});
    //
    // Once the state of Promise is fulfilled/resolved or rejected,
    // following is executed
    //
    loginPromise.then(function(response){
        console.log("User name: " + response.firstname);
        console.log("Completed async operation...");
    }, function(error) {
        console.log(error.message);
    });
    console.log("Completed sync operation...");
    
  • Auth.js: Returns a promise object. Invokes get API on User service as a resolve.
    // Promise needs to be imported when executing a module using Node
    //
    var Promise = require("promise");
    var User = require("./User");
    var userService;
    
    function Auth() {
        userService = new User();
    }
    
    Auth.prototype.login = function(user) {
        return new Promise(function(resolve, reject) {
            if(user.username != "" && user.password != "") {
                resolve(userService.get(user));
            } else {
                if(user.username == ""){
                    reject({status:1, message: "Username is invalid"});
                } else {
                    reject({status:2, message: "Password is invalid"});
                }
            }
        });
    }
    module.exports = Auth;
    
  • User.js: Returns a promise object. Resolves with a User object
    // Promise needs to be imported when executing a module using Node
    //
    var Promise = require("promise");
    
    function User() {
    }
    
    User.prototype.get = function(user) {
        return new Promise(function(resolve, reject) {
            setTimeout(function() {
                resolve({username: user.username,
                            firstname: 'Ajitesh',
                            lastname: 'Shukla',
                            age: 40,
                            location: 'Hyderabad',
                            twitter: 'vitalflux',
                            url: 'http://www.vitalflux.com'});
            }, 5000);
        });
    };
    
    module.exports = User;	
    

 

Ajitesh Kumar
Follow me
Latest posts by Ajitesh Kumar (see all)

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. For latest updates and blogs, follow us on Twitter. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking. Check out my other blog, Revive-n-Thrive.com
Posted in Javascript, UI. Tagged with , .

Leave a Reply

Your email address will not be published. Required fields are marked *