Как обрабатывать несколько запросов Google Places API внутри цикла в NodeJS? - PullRequest
0 голосов
/ 25 августа 2018

У меня есть цикл, который анализирует длинный массив точек GPS, затем я выбираю несколько точек в соответствии с тем, что мне нужно.
Для каждой точки GPS я хочу найти места вокруг.

Как сделать так, чтобы каждый ответ был отделен от других?

Вот код внутри цикла, он работает, когда у меня есть 1 GPS-точка, но с большим это не так:

Цикл маршрута GPS, сохраненный в хеш-таблице:

for (let indexI = 0; indexI < path_hash.length; indexI++) {
    for (let indexJ = 0; indexJ < path_hash[indexI].length - 2; indexJ++) {

...
Подготовьте запрос URL:

location = path_hash[indexI][indexJ].data.coords.latitude + "," + path_hash[indexI][indexJ].data.coords.longitude;
var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?" + "key=" + key + "&location=" + location + "&radius=" + radius + "&sensor=" + sensor + "&types=" + types + "&keyword=" + keyword;

...
Выполнить запрос:

https.get(url, function (response) {
    var body = '';
    response.on('data', function (chunk) {
        body += chunk;
    });

    response.on('end', function () {
        var places = places + JSON.parse(body);
        var locations = places.results;
        console.log(locations);
    });

}).on('error', function (e) {
    console.log("Got error: " + e.message);
})  

1 Ответ

0 голосов
/ 25 августа 2018

Используя вашу функцию, вы можете сделать это следующим образом

// Turn the callback function into a Promise
const fetchUrl = (url) => {
  return new Promise((resolve, reject) => {
    https.get(url, function (response) {
      var body = '';
      response.on('data', function (chunk) {
        body += chunk;
      });

      response.on('end', function () {
        var places = places + JSON.parse(body);
        var locations = places.results;
        resolve(locations) // locations is returned by the Promise
      });

    }).on('error', function (e) {
      console.log("Got error: " + e.message);
      reject(e); // Something went wrong, reject the Promise
    });
  });
}

// Loop the GPS path, saved in hash table
...

// Prepare the urls
...

const GPSPoints = [
  'url1',
  'url2',
  ...
];

// Fetch the locations for all the GPS points
const promises = GPSPoints.map(point => fetchUrl(point));

// Execute the then section when all the Promises have resolved
// which is when all the locations have been retrieved from google API
Promise.all(promises).then(all_locations => {
  console.log(all_locations[0]); // Contains locations for url1
  console.log(all_locations[1]); // Contains locations for url2
  ...
});
...