0

I am making a request to predicthq API

app.get("/test", (req, res) => {
  // [0] IS THE LONGITUDE 
  request.get("https://api.predicthq.com/v1/events/?q=Minnesota&limit=10", {
    headers
  }, (err, data) => {
    var results = JSON.parse(data.body).results;
    var serverRes = [];

    for (var i in results) {

      getGeo(results[i].location[1],   results[i].location[0]).then(v => {
        serverRes[i] = v;
      })
    } //end of for loop

    res.send(serverRes)

  }); // end of request call
}); //end of GET CALL

//ASYNC FUNCTIOON
function getGeo(lat, long) {
  return new Promise(resolve => {
    geocoder.reverse({
      lat: lat,
      lon: long
    }, function(err, res) {
      resolve(res)
    });
  });
}
$(document).ready(function() {
    $("button").on("click", () => {
        console.log("Button Clicked");
        $.get("/test",  function(data, status){
            console.log("data", data)
        });
    });//end of button clicked
}); 

to get a list of events. When I get the response I want to convert the lat, long of the response to an address and put it in an array variable. When I get the response from the server it gives me a list of empty arrays, How do I make the for loop wait until the geocoder.reverse gets the data, then move on to the other lat, long

2 Answers 2

2

Use that for loop to put those promises into an array, then use Promise.all to wait for them to resolve.

var results = JSON.parse(data.body).results;
var geoPromises = [];

for (var i in results) {
  var promise = getGeo(results[i].location[1],   results[i].location[0]);
  geoPromises.push(promise);
}

Promise.all(geoPromises).then(vs => {
  res.send(vs);
});
Sign up to request clarification or add additional context in comments.

Comments

0

Have you tried async await? Looking at it I think this could work for you.

$(document).ready(function() {

$("button").on("click", async () => {
    console.log("Button Clicked");
     await $.get("/test",  function(data, status){
        console.log("data", data)
    });
});//end of button clicked

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.