How to break GlideQuery forEach loop

TT3
Kilo Guru

I have below script, I need to exist the loop when variable i is 2. However, break or return statement does not work here and ServiceNow keeps iterating till the end.

Any idea about how to exist foeEach?

var i = 0;
//There are 4 records with this condition
new GlideQuery(Constants.Order_Item_Table)
	.where('u_parent_inventory_id', '123')
	.select('u_inventory_id')
	.forEach(function (orderItem) {
  	   gs.print(orderItem.u_inventory_id);
           i=i+1;
  	   gs.print(i);
           if (i == 2){
  	    gs.print('in if'); //It prints, but continues with loop
            return;
           }
	});
1 ACCEPTED SOLUTION

Hitoshi Ozawa
Giga Sage

To break out, throw an exception instead of return.

Example:

var BreakException = {};

try {
    var i = 0;
    //There are 4 records with this condition
    new GlideQuery(Constants.Order_Item_Table)
        .where('u_parent_inventory_id', '123')
        .select('u_inventory_id')
        .forEach(function(orderItem) {
            gs.print(orderItem.u_inventory_id);
            i = i + 1;
            gs.print(i);
            if (i == 2) {
                gs.print('in if'); //It prints, but continues with loop
                throw BreakException;
            }
        });
} catch (e) {
    if (e != BreakException) throw e;
}

Else, use GlideRecord instead when there is a need to break.

var i = 0;
var gr = new GlideRecord(Constants.Order_Item_Table);
gr.addQuery('u_parent_inventory_id', '123');
gr.query();
while (gr.next()) {
  var id = gr.u_parent_inventory_id;
  gs.print(gr.u_inventory_id);
  i=i+1;
  gs.print(i);
  if (i == 2){
    gs.print('in if'); //It prints, but continues with loop
    return;
  }
}

View solution in original post

7 REPLIES 7

vkachineni
Mega Sage

can you try 

break;

instead of return;

vkachineni
Mega Sage

Is there a selectOne option instead of selecting more and looping

Allen Andreas
Tera Patron

Hi,

You could just use .limit()?

It's preferable to use this before your .select line, example:

new GlideQuery('task')
    .orderBy('priority')
    .limit(10) // Good: calling GlideQuery's limit method
    .select('assigned_to', 'priority', 'description')
    .forEach(generateReport);

https://developer.servicenow.com/blog.do?p=/post/glidequery-p6/

Please mark reply as Helpful/Correct, if applicable. Thanks!

Actually, there is some check in forEach, just to make question simple I didn't mentioned here. However, based on check I would like to stop looping and come out of forEach.