Sunday, 4 June 2017

Remove the duplicate blocks from callback function

I'm writing a node js program that has to follow the below properties.

  1. Check if access token is available in session(session.user.accessToken), if that doesn't exist, console.log a message.
  2. If the access token is available, check if there is session.attributes.isUserName, if it is there, console.log('The values are there');, if it is not there call the callback method, console.log('The values are there');.
  3. Basically the code is getting duplicated.

Below is my code.

if (!session.user.accessToken) {
       console.log('Token is not available');
    } else {
        if (!session.attributes.isUserName) {
         getUserDetailsFromToken(session, function (err) {
            if (!err) {
               //print the user's data.
                console.log("UserName is " + session.attributes.userName);
            }
        });
        } else{
             //print the user's data.
             console.log("UserName is " + session.attributes.userName);
        }

        }
    }

Here session.attributes.userName that we are printing is same, just that the call back getUserDetailsFromToken checks and sets a variable. Is there a way that I can get the console.log("UserName is " + session.attributes.userName); out of code and use it seperately? this is a sample code that I've provided, I've 126 lines of code in my application, those have to be duplicated, once inside callback (if condition), and another outside callback (else condition).

Please let me know how can I optimize this.

Thanks



via user3872094

No comments:

Post a Comment