0

I'm getting all sorts of weird results in the console with what I'm trying to do and I can't figure it out. What is also a problem is that on every fetch, the result is not always the same - I'll get one of my objects only (and sometimes multiple times in the same call?), or both, or none at all, but they are never combined properly like I want.

The result I am trying to get:

At the end of the function, I want to get a new combined object array as a result of two fetches, which should be in this format and all objects between the same brackets, ideally:

[
    {
        keys: items,
    },
]

Like above, for these fetches the combined object array should have 4 objects (attribute tables). For the first fetch, it will fetch 1 attribute table, and the second will fetch 3 attribute tables.

Any idea how I can fix my fetch to work every time, only return one of each fetch, and combine them into one object array?

HTML

<button onclick="getData()">Get Data</button>

JS

let combined_attTable = [];
let attTable = [];
let attTable_p = [];

function getData() {

  //First pulling attributes for single coordinates
  fetch('https://hazards.fema.gov/gis/nfhl/rest/services/MapSearch/MapSearch_v5/MapServer/0/query?where=&text=&objectIds=&time=&geometry=%7B%22points%22%3A%5B%5B-89.0000%2C40.5555%5D%5D%7D&geometryType=esriGeometryMultipoint&inSR=4326&spatialRel=esriSpatialRelIntersects&distance=&units=esriSRUnit_Foot&relationParam=&outFields=*&returnGeometry=false&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&havingClause=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&historicMoment=&returnDistinctValues=false&resultOffset=&resultRecordCount=&returnExtentOnly=false&datumTransformation=&parameterValues=&rangeValues=&quantizationParameters=&featureEncoding=esriDefault&f=pjson')
    .then(function(response) {
      return response.json();
      console.log("response recieved from the fetch");
    })
    .then(function(data) {
      appendData(data);
    })
    .catch(function(err) {
      console.log('error: ' + err);
    });

  //Handle data for the point coordinate fetch
  function appendData_P(data) {
    for (let obj of data['features']) {
      attTable_p = data['features'].map(({
        attributes
      }) => attributes);
    }
  }

  // Now pulling linear coordinates attributes:
  fetch('https://hazards.fema.gov/gis/nfhl/rest/services/MapSearch/MapSearch_v5/MapServer/0/query?where=&text=&objectIds=&time=&geometry=%7B%22paths%22%3A%5B%5B%5B-92.555%2C40.888%5D%2C%5B-92.333%2C40.888%5D%5D%5D%7D&geometryType=esriGeometryPolyline&inSR=4326&spatialRel=esriSpatialRelIntersects&distance=&units=esriSRUnit_Foot&relationParam=&outFields=*&returnGeometry=false&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&havingClause=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&historicMoment=&returnDistinctValues=false&resultOffset=&resultRecordCount=&returnExtentOnly=false&datumTransformation=&parameterValues=&rangeValues=&quantizationParameters=&featureEncoding=esriDefault&f=pjson')
    .then(function(response) {
      return response.json();
      console.log("response recieved from the fetch");
    })
    .then(function(data) {
      appendData(data);
    })

    .catch(function(err) {
      console.log('error: ' + err);
    });

  //Handle data for the linear coordinate fetch
  function appendData(data) {
    for (let obj of data['features']) {
      attTable = data['features'].map(({
        attributes
      }) => attributes);
    }
  }

  // Now combine the attribute tables into one unnested array
  combined_attTable.push(attTable);
  combined_attTable.push(attTable_p);
  //console.log(attTable_p);
  //console.log(attTable);
  console.log(combined_attTable);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Jack
  • 53
  • 8
  • 1
    `fetch()` is asynchronous. You're pushing to `combined_attTable` before they have completed. Use `async/await` to order things. – Barmar Aug 02 '22 at 15:44
  • 1
    Or if you want to do both fetches concurrently, put both of the returned promises in an array, then use `Promise.all()` to wait for them both. – Barmar Aug 02 '22 at 15:45
  • @Barmar Thank you for the pointing me in the right direction, you are an ultimate being. That was quite a rabbit hole and [I solved my issue](https://jsfiddle.net/tsxp6Lqw/). – Jack Aug 02 '22 at 18:46

0 Answers0