Home > Software design >  AppScript: Function called is not returning value as argument when put in a loop?
AppScript: Function called is not returning value as argument when put in a loop?

Time:03-03

Hi all great minds of stackoverflow, when I log "paySlip" variable at the end of "paySlipMethod()" function, the URLs are retrieved. However, when I call the function in "generatePaySlips()" function in a loop, I get "null", let alone pushing the URLs into "links" array... please enlighten me, a billion thanks to you all.

function generatePaySlips(paySlip){

  const month = currentSheet.getRange("B1").getDisplayValues();
  const year = currentSheet.getRange("C1").getDisplayValues();
  const data = currentSheet.getRange(3,2,currentSheet.getLastRow()-2,21).getDisplayValues();

  let errors = [],links = [];
  data.forEach(row => {
      try{
        paySlipMethod (month,year,row[0],row[1],row[2]...blabla,paySlipTemp,tempFolder,pdfFolder,paySlip);
        errors.push(["OK"]);
        links.push([paySlip]);
        Logger.log(paySlip);
      } catch(err){
        errors.push(["error"]);
      }
  });

  currentSheet.getRange(3,22,currentSheet.getLastRow()-2,1).setValue(errors);
  currentSheet.getRange(3,23,currentSheet.getLastRow()-2,1).setValue(links);


function paySlipMethod(month,year,eng_name....paySlipTemp,tempFolder,pdfFolder,paySlip) {
 const tempSlip = paySlipTemp.makeCopy(tempFolder);
 const tempPaySlip = DocumentApp.openById(tempSlip.getId());
 const body = tempPaySlip.getBody();

 body.replaceText("{month}",month);
 blabla...the rest

 tempPaySlip.saveAndClose();
 const pdfContentBlob = tempSlip.getAs(MimeType.PDF);
 var paySlip = pdfFolder.createFile(pdfContentBlob).setName(month " " year " - " eng_name).getUrl();
 tempFolder.removeFile(tempSlip);

 return paySlip;
}

CodePudding user response:

As much i understand your requirement you want to push the URL returned from paySlipMethod into links array. But I can't see any variable which is storing the returned URL here:-

 paySlipMethod (month,year,row[0],row[1],row[2]...blabla,paySlipTemp,tempFolder,pdfFolder,paySlip);

Try this modification :-

   try{
        var paySlip = paySlipMethod(month,year,row[0],row[1],row[2]...blabla,paySlipTemp,tempFolder,pdfFolder,paySlip);
        errors.push(["OK"]);
        links.push([paySlip]);
        Logger.log(paySlip);
      } catch(err){
        errors.push(["error"]);
      }

Here var paySlip will store the returned URL which you can use later.

  • Related