1

这就是我想要实现的目标,我正在调用一个 api,导致基于邮政编码和半径的多个调用。根据人口密度,结果可能少至一个或多至二十个。此调用的结果作为没有信息的数组返回到多个条目。我需要做的是获取多个单独的数组并创建一个数组,该数组删除所有空数组并将每个单独的数组附加到一个数组中。当前进行多次调用的代码是:

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) {

        });
   };

console.logs 到 buildOutput 的结果如下所示:

[[]]
[[]]
[[]]
[[{"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"}]]
[[]]

所以这个半径为 4 英里的邮政编码的结果是 7 个邮政编码,其中 2 个当前有条目。对此的帮助将不胜感激,将七个单独的调用放入一个数组中,然后删除任何零条目。

4

1 回答 1

0

也许以下内容会有所帮助,您的代码在同一个数组上循环两次没有多大意义,您的内部数组与您的外部数组相同。

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)
    )
  }
)
于 2018-05-08T03:26:06.327 回答