1

I am having a weired issue that func1(), which is coded in front of func2(), is executed after func2() in my custome widget.

The widget draws a buffer on a click event, and when a "Show Results" button is clicked, it counts the number of facilities within the buffer. Below is a code sample:

var totalFac = 0 // Store the total number of facilities globally
var globalGeometry = null; // Store the query geometry globally

onShowResultsClick: function() {
  totalFac = 0; // Initialize
  this.facLayer = new FeatureLayer("https://link/to/layer");
  var query = new Query();
  query.geometry = globalGeometry;
  this.facLayer.queryFeatures(query, function(result) {
    var features = result.features;
    totalFac = features.length;
    console.log(totalFac);
  });
  console.log(totalFac); // Executed first
},

The two console.log() functions are executed reversely. As totalFac is initialized as 0, the console shows 0 firstly. The the real value of totalFac is shown after the 0. In fact, if totalFac is initialized as 888, the console will show 888 firstly, then the real value. Apparently queryFeatures() is executed last, behind the second console.log().

How come that a function coded in front of the next function is executed afterwards?

1

The reason why the last console log (the one at the end of onShowResultsClick) executes first it that the first console log (the other one) is waiting for the query to be solved.

The queryFeatures function do a request to the server to obtain the features. In other words you are telling execute this code (the function you pass as a parameter) when the request is over. It is an asynchronous event, and because of that JavaScript continues executing the code till the request is complete (*)

(*) It is not exactly like this, I simplify to give you the idea. Roughly speaking, there is something call "event loop". Asynchronous events are not executed as soon as they end, instead there are executed in a determined step of the loop.

|improve this answer|||||
  • Thank you. This makes a lot of sense. How can I force the latter function to wait and run after queryFeatures is completed? – PacmanKX Jan 29 at 14:35
  • You could run the code (for example wrapped in a function), at the end of the function that handles the request success return. In that way it will always execute once the request it is completed successfully. You could also transform the code a bit and use async/await for a similar behavior. – cabesuon Jan 29 at 18:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.