Search code examples
node.jsaws-lambdaglobal-variables

Can't update global variable within function AWS lambda node


I'm trying to write an AWS lambda function webhook that at first receives a post request with an ID. Then once it has the ID it does a bunch of other things with it. In the very first step, everything within the function works as expected and the console.log returns the correct value of the ID, and it appears correctly in the body of the response.

But I have not been able to update the global variable newDealId from within the function. The second console.log always returns the initial value of the newDealId which is "". Why is this?

var newDealId = "";

exports.handler = (event) => {

    
    // Grab ID From New Deal Post Request
    newDealId = JSON.stringify(event.id); 
    console.log("DEAL ID:"+newDealId);
    
    const response = {
        statusCode: 200,
        body: newDealId, 
         
    };
    return response;
};

console.log("DEAL ID 2: "+newDealId); // always returns "" as value

Solution

  • The console.log function is returning "" because when the script is run the function itself does not run but is defined. The only expressions that run are

    var newDeal = "";
    /* and */
    console.log("DEAL ID 2: " + newDeal);
    

    Then when the lambda is hit and handler runs only the defined function runs. Your console.log statement is outside of the function and therefore does not run.

    // this is what runs
    exports.handler = (event) => {
        
        // Grab ID From New Deal Post Request
        newDealId = JSON.stringify(event.id); 
        console.log("DEAL ID:"+newDealId);
        
        const response = {
            statusCode: 200,
            body: newDealId, 
             
        };
        return response;
    };
    

    I would try this. It should behave more like what you're expecting.

    exports.handler = (event) => {
        var newDealId = "";   
    
        function doesStuff() {
            // Grab ID From New Deal Post Request
            newDealId = JSON.stringify(event.id); 
            console.log("DEAL ID:"+newDealId);
        
            const response = {
                statusCode: 200,
                body: newDealId, 
             
            };
            return response;
        }
    
        console.log("DEAL ID 2: "+newDealId);
    
        return doesStuff();
    };