forEach not making function call in Scheduled Job

James Michaels1
Giga Expert

For some reason I can't get forEach to work in either a scheduled job or background script in ServiceNow. The below code works properly outside of SNow with the gs swapped for console. If I redo the code to use a regular for loop it works just fine in SNow as well. When I run this in SNow it does the first log but not the one inside the function. As far as I can tell there are no errors thrown. Is there something I'm doing wrong?

var testedArray = ['1','2'];

gs.log(testedArray);

function makeCall(element,index,array) {gs.log(element);}

testedArray.forEach(makeCall);

/*for (var i = 0;i<testedArray.length;i++){

  makeCall(testedArray[i]);

}*/

EDIT: I am running Geneva Patch 6 Hotfix 2

EDIT 3: Removed Edit 2 about using for in as it was incorrect. The problem seems to be with forEach only

1 ACCEPTED SOLUTION

James Michaels1
Giga Expert

Looks like the answer is that forEach was added in ES 5 and SNow added support for ES 5 in Helsinki so array.forEach as well as anything else added in ES 5 won't work in Geneva.



See here for the details: JavaScript engine upgrade


View solution in original post

5 REPLIES 5

bala_sn
Kilo Expert

Hi James,



I tried this in Helsinki. And it works just fine. I ran the following code in background script.



var testedArray = ['1','2'];  


gs.print(testedArray);  


function makeCall(element,index,array) {gs.print(element);}  


testedArray.forEach(makeCall);



bala


Interesting. I'm still on Geneva unfortunately. I tried it with the gs.print but am still getting the same result. It logs the array from line 2 but doesn't log from the function.


I just tested this script in both Helsinki and geneva.


var testedArray = ['1','2'];


gs.print(testedArray);


function makeCall(element,index,array) {gs.print(element);}


testedArray.forEach(makeCall);



Doesn't work in Geneva. Wonder why!



But the other one-


  1. var trackingArray = [449044304137821,149331877648230,020207021381215,403934084723025];  
  2. for (var i in trackingArray){  
  3.         gs.print(trackingArray[i]);   //used gs.print for running in background script
  4. }  

works in both versions for me.


I jumped the gun on the for in a bit. I was calling a function from within the for in and it was only logging the first element. I cleaned up the code like with the forEach and it worked just fine. I think this is unrelated to the forEach and I just have a function problem with the for in.