Search code examples
promiseparse-serverparse-cloud-code

Execute multiple http request - Parse Cloud Code


i have an array of stores, where the address and some other things are stored.

Now I want to iterate through this array and geocode the lat / lng coords and save them to the database.

With the code below I get double or triple entries of the same store. Do I miss something with the scope here?

Thanks!

var promises = [];

data.forEach(function (element, index) 
{
    var addressString = element.plz + " " + element.stadt + "," + element.adresse;
    var url = encodeURI("https://maps.googleapis.com/maps/api/geocode/json?address=" +
        addressString);
    var promise = Parse.Cloud.httpRequest({
        method: "GET",
        url:url
    }).then(function (http) //SUCCESS
        {
            var geocodedObject = new Parse.Object("GeocodedStores");
            geocodedObject.set("storeID", element.id);
            geocodedObject.set("Latitude", http.data.results[0].geometry.location.lat);
            geocodedObject.set("Longitude", http.data.results[0].geometry.location.lng);

            return geocodedObject.save(null, {
                useMasterKey: true
            });
        },
        function (http, error) 
        {
            response.error(error);
        });
    promises.push(promise);
});

return Parse.Promise.when(promises);

Solution

  • Finally found a working solution. It looked like it was a problem with the scope. I put the code in a seperate function and added this returned promise to an array.

    var fn = function(element, geocodedObject)
    {
        var addressString = element.plz + " " + element.stadt + "," + element.adresse;
        var url = encodeURI("https://maps.googleapis.com/maps/api/geocode/json?address=" +
            addressString);
    
        Parse.Cloud.httpRequest({
        method: "GET",
        url: url
        }).then(function(http)
        {   
    
            geocodedObject.set("storeID", element.id);
    
            geocodedObject.set("Latitude", http.data.results[0].geometry.location.lat);
            geocodedObject.set("Longitude", http.data.results[0].geometry.location.lng);
    
            geocodedObject.set("address", addressString);
    
            return geocodedObject.save(null, {
                useMasterKey: true
            });
    
        });
    }
    
    var promises = [];
    
    for (var k = 0;k<data.length;k++) 
    {
        var geocodedObject = new Parse.Object("GeocodedStores");
        promises.push(fn(data[k], geocodedObject));
    }
    
    
    
    Parse.Promise.when(promises).then(function () {
        response.success("DONE");
    });