Getting undefined value using GetReference method outside callback function

vivek72
Tera Guru

Hi,

I am using getReference method to check value set in a variable but getting undefined in alert:

Please let me know if I am missing anything, result in variable 'gr' should be test but I am getting undefined.

It's giving 'test' when I am trying to put alert inside callback function but the problem is only when this alert is set outside callback function.

I need to check this value to write my other code so it should return correct value outside callback function as well.

var gr;

var a1 = g_form.getReference('assignment_group', check);
function check(a1) {

if (a1.u_system == 'test') {

gr = a1.u_system;
}

}
alert(gr);

Thanks,

Vivek

1 ACCEPTED SOLUTION

Abhijit4
Mega Sage

Hi Vivek,

When you use getReference method with callback function then it acts as Aynchronous call which will execute your alert line before your callback function that is the reason it is showing value as empty.

If you want to check mandatory field based on some server side data then you would need to make synchronous call which is something like below,

var a1 = g_form.getReference('assignment_group');
if (a1.u_system == 'test') {
gr = a1.u_system;
}
alert(gr);

ServiceNow don't recommend synchronous call on client side. However, if you have such requirement then it should be fine.

Let me know if you have any further queries.

Please mark this as Correct or Helpful if it helps.

Thanks and Regards,
Abhijit

By marking my response as correct or helpful, you contribute to helping future readers with similar issues.
Regards,
Abhijit
ServiceNow MVP

View solution in original post

10 REPLIES 10

Hi Abhijit,

thanks for your reply.

It works this way, only problem as you mentioned this is not as per Servicenow best practices.

I will check with customer if there is no other way.

Thanks,

Vivek