QueryTask: Get Value out of executeForCount()

430
3
12-16-2020 03:03 PM
XuanKuai
New Contributor III

How to get the value assigned inside queryTask.executeForCount() to use elsewhere outside of it? In the following example, I want flag = 1 when count > 0. But when I access flag outside of queryTask.executeForCount(), the value is not changed.

Note: the code runs in Web AppBuilder Developer Edition.

...
var flag = 0;
queryTask.executeForCount(query, lang.hitch(this, function(count) {
  if(count > 0) {
    flag = 1; // Suppose this one fires instead of flag = 0
  } else {
    flag = 0;
  }
}));
console.log(flag); // Still returns 0, I want it to return 1

 

0 Kudos
3 Replies
RobertScheitlin__GISP
MVP Esteemed Contributor

The answer is pretty simple you are logging the value of flag var before the aSync process is complete.

var flag = 0;
queryTask.executeForCount(query, lang.hitch(this, function(count) {
  if(count > 0) {
    flag = 1; // Suppose this one fires instead of flag = 0
  } else {
    flag = 0;
  }
}));
// this line is executed before the executeForCount method returns
console.log(flag); // Still returns 0, I want it to return 1

What you would need is something like this:

var flag = 0;
queryTask.executeForCount(query, lang.hitch(this, function(count) {
  if(count > 0) {
    flag = 1; // Suppose this one fires instead of flag = 0
  } else {
    flag = 0;
  }
  console.log(flag);
}));

 

0 Kudos
XuanKuai
New Contributor III

Thank you for your reply. Yes I noticed that. In fact I really need the flag value to use it outside of the function. Is there a way to have the following code execute after this is completed? Or more simply, since I am looking for the count, is there a way to get the count out of it for following use?

0 Kudos
RobertScheitlin__GISP
MVP Esteemed Contributor

Xuan,

   You will need to start using function based programming methods and not in line code, like you are now. The code that needs to access the flag var needs to be called from the executeForCount handler. So normally I would put any code that needs access to a async process result inside its own function that is only called inside the result of the async promise result function.

0 Kudos