jjones312
jjones312

Reputation: 695

When calling a function result returns "undefined"

I'm attempting to call a function from another function within Google Apps Script, but during the testing, it keeps returning "undefined" in the logger. Below are the functions with a bit of explanation.

The function here will get the email address of the active users. When run by itself it returns the email address just fine. (i've added the logger.log line so that you can try and see.

   function getUser() {
   //Uses the base class to get acive user's email
   var email = Session.getActiveUser().getEmail();
   //Logger line is for testing only and would be removed once final
   Logger.log(email);
   }

The purpose of this function will be to add addition information to the last row of the spreadsheet for certain columns. This would be called onFormSubmit. I'm attempting to get the active user email address by calling the above function. I know I can just uncomment the one line above the variable requestUser but I'm hoping to call other functions that do specific tasks, trying to learn and expand my understanding i guess.

   function addToPTO(){
     var ss1 = SpreadsheetApp.getActiveSpreadsheet();
     var sheet = ss1.getSheetByName('Form Responses');
     var data = sheet.getDataRange().getValues();
     var data2 = sheet.getDataRange().getLastRow();

     //var getUserInfo = Session.getActiveUser().getEmail();
     var reqeustUser = getUser();
     Logger.log(reqeustUser);

     for (var i = 0; i < data.length; i++) {
       var row = data[i];
       var status = row[8];
       var comment = row[9];   
       if (status == "") {
         data[i][8] = "Pending";
         }
     }    
     sheet.getDataRange().setValues(data);  
   }

Upvotes: 1

Views: 202

Answers (1)

C. S.
C. S.

Reputation: 813

You can do one of two things:

return email in function getUser()

It would look something like this:

function getUser() {
   // moved Logger one line above, it will not log if it occurs AFTER the return statement
   Logger.log(email);
   return Session.getActiveUser().getEmail();
}

function addToPTO(){
     var ss1 = SpreadsheetApp.getActiveSpreadsheet();
     var sheet = ss1.getSheetByName('Form Responses');
     var data = sheet.getDataRange().getValues();
     var data2 = sheet.getDataRange().getLastRow();

     var reqeustUser = getUser();
     Logger.log(reqeustUser);

     for (var i = 0; i < data.length; i++) {
       var row = data[i];
       var status = row[8];
       var comment = row[9];   
       if (status == "") {
         data[i][8] = "Pending";
         }
     }    
     sheet.getDataRange().setValues(data);  
}

Upvotes: 1

Related Questions