Query Result to a Global Variable?

11-11-2019 04:18 PM
New Contributor III


I'm trying to get the result from a query and pass it out to a global variable and do something with it outside of the require().  Is it possible to do so?  The current code that I put together from various sources does not work, please any help or advice would be tremendous.  Thanks.

  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>ArcGIS JavaScript Tutorials: Create a Starter App</title>
    html, body, #viewDiv {
      padding: 0;
      margin: 0;
      height: 90%;
      width: 100%;
  <link rel="stylesheet" href="https://js.arcgis.com/4.13/esri/css/main.css">
  <script src="https://js.arcgis.com/4.13/"></script>
	var fAttribute; //global variable
    ], function(Map, MapView, FeatureLayer, GraphicsLayer, Graphic) 

		var map = new Map({
			basemap: "topo-vector"
		var featureLayer = new FeatureLayer({
			url: "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/Trailheads_Styled/FeatureServer/0",

		var graphicsLayer = new GraphicsLayer();
		var view = new MapView({
			container: "viewDiv",
			map: map,
			center: [-118.80500,34.02700],
			zoom: 13
		function QueryParkName(featureLayer)
			var query = featureLayer.createQuery();
			query.where = "TRL_NAME = 'Glade Trail - Topanga'";
			query.outFields = ["*"];
				fAttribute = response.features[0].attributes.PARK_NAME; 
				console.log("Result: "+fAttribute); //display correctly
                console.log("Result Outside of QueryParkName: "+fAttribute); //display undefined	
	function DisplayName()
		console.log("Park Name: "+fAttribute); //display undefined. 
  <div id="viewDiv"></div>
0 Kudos
1 Reply
MVP Honored Contributor

It's not a problem of accessing the variable outside the require, but rather of timing. If you add a button to the body to run the function DisplayName, clicking the button will show the queried park name.

  <div id="viewDiv"></div>
  <button onclick = 'DisplayName()'>Results</button>

In your code, the query hasn't started (line 67) or completed (line 60) before you display the variable. You have to wait for the query to complete before you can see the results.