2

I am trying to make a web API call twice inside of a loop, then wait until the webAPI has returned before pushing the returned values as a subarray within a larger array. Here's my code:

var latlngPairs = [];
function extractLatLongPairs(jsonobj){
    for(var i = 0; i<10; i++){
        let promises = [googlePlace(jsonobj[i]['From LID']), googlePlace(jsonobj[i]['To LID'])];

        Promise.all(promises).then((results) => {
            var temp2 = [results[0], results[1]];
            latlngPairs.push(temp2);
            console.log(latlngPairs);
        });
    }
}

The googlePlace function being called in promises:

function googlePlace(airport){
    https.get('https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=' + airport + '&inputtype=textquery&fields=geometry', (resp) => {
        let data = '';

        // A chunk of data has been recieved.
        resp.on('data', (chunk) => {
            data += chunk;
        });

        //All data is returned
        resp.on('end', () => {
            data = JSON.parse(data);
            let obj = {
                name: airport,
                location: data.candidates[0].geometry.location
            };
            console.log('latlong should print after this');
            return Promise.resolve(obj);
            });

        }).on("error", (err) => {
            console.log("Error: " + err.message);

    });
}

I am expecting console.log('latlong should print after this') to print out before latlngPairs is printed. Because the order is vice versa, latlngPairs is filled with subarrays with undefined values. The output is something like:

[
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ],
  [ undefined, undefined ]
]
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this

To be clear, the order I'm rying to achieve is 'latlong should print after this' then ' [[obj, obj], [obj, obj]]. I think I must have some fundamental misunderstanding about how promise.all works, and any help would be much appreciated!

Sanoris
  • 23
  • 3

1 Answers1

2

You need to make your googlePlace function actually return a promise:

function googlePlace(airport) {
    // notice the new Promise here
    return new Promise((resolve, reject) => {
        https
            .get(
                "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=" +
                    airport +
                    "&inputtype=textquery&fields=geometry",
                (resp) => {
                    let data = "";

                    // A chunk of data has been recieved.
                    resp.on("data", (chunk) => {
                        data += chunk;
                    });

                    //All data is returned
                    resp.on("end", () => {
                        data = JSON.parse(data);
                        let obj = {
                            name: airport,
                            location: data.candidates[0].geometry.location,
                        };
                        console.log("latlong should print after this");
                        // notice the resolve here
                        resolve(obj);
                    });
                }
            )
            .on("error", (err) => {
                console.log("Error: " + err.message);
                reject(err.message);
            });
    });
}
Aplet123
  • 33,825
  • 1
  • 29
  • 55