Wait for API data before inserting into collection

Hey guys,

I have been trying to implement a facial recognition API into my meteor project and insert the findings into a collection along with some other data. Once I send the request to the API, it takes a few seconds to process and return the results, which is reasonable but the collection is created with null in the fields that hold the response from the API.

Is there a way to wait until the API gives a response before inserting anything into the collection?

Yes. Can we see your current code?

Hey Rob,

In my main.js file on the Server, I have:

T.get('search/tweets', { q: 'keyword since:2016-05-20', count: 50 }, Meteor.bindEnvironment(function(err, data, response) {

      for(var i = 0; i < 50; ++i) {


  try{
            Unirest.get(//api url)
         .header("X-Mashape-Key", //key)
        .header("Accept", "application/json")
        .end(function (result) {
            value1 = //value from api
            value2 = //value from api
            value3 = //value from api
        }
        
        })
   }
        catch(err){
          console.dir(err);
        }

Collection.insert({Value1: value1, Value2: value2, Value3: value3}, , function(error){
          if(error)
          console.log(error);
        });

}

}))

I don’t know the specifics of your application but if I were you, I’d just use the standard HTTP package that ships with meteor. It is already synchronous. You can do what you want like this:

const res = HTTP.get('someUrl');
Collection.insert({value1: res.data.value1});
3 Likes

I will try this out! How do I send in the parameters to the API? Such as the headers I have while using Unirest.

1 Like

Here are the docs for it: http://docs.meteor.com/api/http.html

but a quick answer would be like this.

HTTP.get('someUrl', {headers: {'X-Mashape-Key': key, 'Accept': 'application/json'}});
1 Like

The synchronous part works perfect, thank you! The only issue I’m having now is that when I put the API call within a for loop, it keeps returning the same value as the first API call over and over again. With my Unirest call, it would return the value of each individual call. Is there a way to go around this?

I got the solution to the response from the API not changing while in a for loop. Instead of const res, just use var res and it works fine.