Search code examples
javascriptarraysnode-fetch

multiple calls from for loop to array, then drop 0 length results


This is what I am trying to achieve, I am making one call to an api that results in multiple calls based on zip code and radius. Based on population density results could be as few as one result or as many as twenty. The results of this call are returned as arrays of no information to multiple entries. The thing that I need to do is to take the multiple individual arrays and create one array that removes all the empty arrays and appends each individual array into one. the code that currently makes the multiple calls is:

const https = require('https');
const fetch = require('node-fetch');
var zipcodes = require('zipcodes');

var food_truck_zip = '29615'

var userzip = food_truck_zip

var user = zipcodes.lookup(userzip);
//console.log(user);

var rad = zipcodes.radius(userzip,4);

array = rad;
for (var i=0; i<array.length; i++)
    var zipsArray = array;
    for(let i=0;i<zipsArray.length; i++) {
      fetch('https://36245d69.ngrok.io/api/vendor_filter/?zipCode=' + 
      zipsArray[i])
        .then(response => {
         return response.json();
        })
        .then(function handleData(data) {
          var buildOutput = [];
          buildOutput.push(data);
          console.log(JSON.stringify(buildOutput));
        })
        .catch(function handleError(error) {

        });
   };

and the results of the console.logs to buildOutput look like this:

[[]]
[[]]
[[]]
[[{"truckName":"Chuck Truck","locationName":"Butler Springs 
Estate","locationAddress":"Butler Springs Road","beginning":"10:00 
am","ending":"05:00 pm"},{"truckName":"Henry's Hog 
Hauler","locationName":"Strange Brew","locationAddress":"1100 Wade 
Hampton","beginning":"06:30 pm","ending":"08:30 pm"}, 
{"truckName":"Chuck Coffee Crusted Salmon","locationName":"The Home 
Base","locationAddress":"Butler Springs Estates","beginning":"04:30 
pm","ending":"06:00 pm"}]]
[[]]
[[{"truckName":"ThoroughFARE","locationName":"Grateful 
Brew","locationAddress":"800 North Pleasantburg","beginning":"04:30 
pm","ending":"07;00 pm"}]]
[[]]

So the results for this zip code with a radius of 4 miles is seven zip codes of which 2 currently have entries. An help with this would really be appreciated, putting the seven individual calls into one array then removing any zero entries.


Solution

  • Maybe the following will help, your code doesn't make much sense to loop over the same array twice, your inner array is the same as your outer.

    function Fail(reason){this.reason=reason;};
    const isFail = o => (o&&o.constructor)===Fail;
    const isNotFail = o => !isFail(o);
    
    Promise.all(
      rad.map(
        zip =>
          fetch('https://36245d69.ngrok.io/api/vendor_filter/?zipCode=' +
          zip)
          .then(response => {
            return response.json();
          })
          .then(function handleData(data) {
            console.log("got data:",JSON.stringify(data));
            return data.map(
              //add zip to item, your question does not show zip but comment askes
              // for zip to be there
              item=>({...item,zip})
            );
          })
          .catch(function handleError(error) {
            err=>new fail([err,zip])
          })
      )
    ).then(
      results => {
        console.log(
          "successes:",
          results
            .filter(isNotFail)
            .filter(item=>!!item.length)//remove empty items
            .reduce((result,item)=>result.concat(item))//flatten array of array to one array
        );
        results.filter(isFail).forEach(
          ([error,zip])=>console.log("failed:",zip,"with error:",error)
        )
      }
    )