logo

NJP

Wrap fix scripts in functions... or else

Import · Apr 06, 2017 · article

We noticed a very odd issue yesterday when running a "no brainer" script to update items in a GlideRecord while next loop:

var gr = new GlideRecord("cmdb_ci");

  gr.addNotNullQuery('u_vulnerability_remediation_group');

  gr.query();

  while ( gr.next() ) {

            try {

                      gr.setValue('u_vulnerability_remediation_group',   '');

                      gr.update();

            } catch(e) {

                      gs.print(e.message);

            }

  }

I have used code like this for years in SNOW and it just works (err.. worked). I have some examples just like this actually checked into source control!

Under Helsinki, the actual results of this script were "intriguing": It deleted a single item and then exited the loop.

After some tinkering I discovered that a function wrapper solved the problem.

//After wrapping the code in a IFFE, the loop continues to update items as expected.

(function() {

  var gr = new GlideRecord("cmdb_ci");

  gr.addNotNullQuery('u_vulnerability_remediation_group');

  gr.query();

  while ( gr.next() ) {

            try{

                      gr.setValue('u_vulnerability_remediation_group',   '');

                      gr.update();

            } catch(e) {

                      gs.print(e.message);

            }

  }

}());

View original source

https://www.servicenow.com/community/developer-blog/wrap-fix-scripts-in-functions-or-else/ba-p/2266449