0

I want to get some data about places using the Google Places API. Thing is, I want to get data from more than 1000 records, per city of the region I'm looking for.

I'm searching for pizzeria, and I want all the pizzerias in the region I've defined. So I have an array like this:

['Pizzeria+Paris','Pizzeria+Marseille','Pizzeria+Nice','Pizzeria+Toulouse']

My objective is to make a single request, then wait 3sec(or more), and then process the second request. I'm using Lodash library to help me iterate.

Here is my code:

function formatDetails(artisan){
  var latitude = artisan.geometry.location.lat;
  var longitude = artisan.geometry.location.lng;
  var icon = artisan.icon;
  var id = artisan.id;
  var name = artisan.name;
  var place_id = artisan.place_id;
  var reference = artisan.reference;
  var types = artisan.types.toString();

  $('#details').append('<tr>'+
  '<td>'+latitude+'</td>'+
  '<td>'+longitude+'</td>'+
  '<td>'+icon+'</td>'+
  '<td>'+id+'</td>'+
  '<td>'+name+'</td>'+
  '<td>'+place_id+'</td>'+
  '<td>'+reference+'</td>'+
  '<td>'+types+'</td>'+
  '</tr>');
} 

var getData = function(query, value){
 $.ajax({
      url: query,
      type: "GET",
      crossDomain: true,
      dataType: "json",
      success: function(response) {
        var artisan = response.results;
        console.log(artisan);
        for (var i = 0; i < artisan.length; i++){
          formatDetails(artisan[i]);
          setTimeout(function(){console.log('waiting1');},3000);
        }
        setTimeout(function(){console.log('waiting2');},3000);
      },error: function(xhr, status) {
        console.log(status);
      },
      async: false
    });  
}




$(document).ready(function(){

var places =
['Pizzeria+Paris','Pizzeria+Marseille','Pizzeria+Nice','Pizzeria+Toulouse'];

  _.forEach(places, function(value, key) {
    var proxy = 'https://cors-anywhere.herokuapp.com/';
    var target_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query='+value+'&key=AIzaSyAClTjhWq7aFGKHmUwxlNUVBzFpIKTkOrA';
    var query = proxy + target_url;
    getData(query, value);
  });




}); 

I've tried a lot of solutions I found on stackoverflow, but no one were working, or I might have done them wrong.

Thanks for your help!

yofisim
  • 372
  • 1
  • 6
  • 17
  • `I've tried a lot of solutions I found on stackoverflow` which ones have you tried? – Jaromanda X Aug 21 '17 at 12:25
  • I tried what you can found here: https://stackoverflow.com/questions/33395048/set-a-delay-in-ajax-call https://stackoverflow.com/questions/18965768/set-a-delay-in-a-repeating-jquery-ajax-function https://stackoverflow.com/questions/17332976/delay-in-ajax-success-not-working https://stackoverflow.com/questions/40829915/i-want-to-delay-jquery-ajax-successful-function – yofisim Aug 21 '17 at 13:55

2 Answers2

0

The fact that $.ajax returns a Promise makes this quite simple

Firstly, you want getData to return $.ajax - and also get rid of async:false

var getData = function(query, value) {
    return $.ajax({
        url: query,
        type: "GET",
        crossDomain: true,
        dataType: "json",
        success: function(response) {
            var artisan = response.results;
            for (var i = 0; i < artisan.length; i++){
                formatDetails(artisan[i]);
            }
        },error: function(xhr, status) {
            console.log(status);
        }
    });  
}

Then, you can use Array.reduce iterate through the array, and to chain the requests together, with a 3 second "delay" after each request

Like so:

$(document).ready(function(){
    var places = ['Pizzeria+Paris','Pizzeria+Marseille','Pizzeria+Nice','Pizzeria+Toulouse'];
    places.reduce((promise, value) => {
        var proxy = 'https://cors-anywhere.herokuapp.com/';
        var target_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query='+value+'&key=AIzaSyAClTjhWq7aFGKHmUwxlNUVBzFpIKTkOrA';
        var query = proxy + target_url;
        return promise.then(() => getData(query, value))
            // return a promise that resolves after three seconds
        .then(response => new Promise(resolve => setTimeout(resolve, 3000)));
    }, Promise.resolve()) /* start reduce with a resolved promise to start the chain*/
    .then(results => {
        // all results available here
    });
});
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
0

The most effective answer is the one above from @jaromandaX. Nevertheless, I also found a workaround with Google Chrome, which will help you to not get your hands dirty with promises.

On Chrome:
1. Open Console
2. Go to network tab
3. Near the options "preserve log" and "disable cache", you have an option with an arrow where you will see the label "No throttling". enter image description here
4.Click on the arrow next to the label, then add.
5. You will be able to set a download and upload speed, and most important, delay between each request.

Kaboom, working with my initial code.

Nevertheless, I changed my code to fit the above answer, which is better to do, in terms of code, speed, etc..

Thanks

yofisim
  • 372
  • 1
  • 6
  • 17