0

I would like to know if it's possible to return a variable in a function after finding the result in a queryTask.

Apparently this is an asynchronous execution but, to be honest, I really need to execute that ..

Here is my simple example I hope you find a solution to remedy it.

  myfunction: function (num) {

    var rft = 0;
    var gedlayer = new FeatureLayer("http:mylink/MapServer/1", {
        mode: FeatureLayer.MODE_ONDEMAND,
        outFields: ["*"]
    });

    var qr = new QueryTask();
    qr.where = "rft=" + num;
    qr.outFields = ["*"];


    gedlayer.queryFeatures(qr, function (featureSet) {
    if (featureSet.features.length > 0) {
    var content = "";
            for (var i = 0; i < featureSet.features.length; i++)
            {
            rft = rft + featureSet.features[i].attributes.rft;
                    }
    }
    },


    function (error) {
        console.log("Error dans la requette de poste source : " + error);
    }
    );



 return rft;
    }    ,
1

You have to use promises to wait for the results, and do whatever you want with them. You can check the related dojo Deferred documentation for better understanding:

require([
 ...
 "dojo/Deferred", 
 ...
 ], function (
    ... 
    Deferred
    ...) {

  myfunction: function (num) {
  var rft = 0;
  var gedlayer = new FeatureLayer("http:mylink/MapServer/1", {
    mode: FeatureLayer.MODE_ONDEMAND,
    outFields: ["*"]
  });

  var qr = new QueryTask();
  qr.where = "rft=" + num;
  qr.outFields = ["*"];

  gedlayer.queryFeatures(qr).then(
    handleQueryResults.then(useResultFromQuery), 
    handleError);
},
handleQueryResults: function(results) {
  var deferred = new Deferred();
  var rft = 0;
  if (featureSet.features.length > 0) {
    var content = "";
    for (var i = 0; i < featureSet.features.length; i++) {
      rft = rft + featureSet.features[i].attributes.rft;
    }
  }
  deferred.resolve(rft);
},
handleError: function(error) {
  console.log("Error dans la requette de poste source : " + error);
},
useResultFromQuery: function (rtf){
  //do whatever you want with rft
}
}
  • my question was how to return the result in the first function, in your answer it's about the function myfuction (), when I call this function, it does not return the result, the type of the return is undefined ! – Kalifornium Mar 11 '18 at 10:24

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.