HTTP.get - undefined

I’m getting undefined while calling fetchFourSquareApi function, though
console.log(responce) is working fine. Something’s wrong with my fetchFourSquareApi function, but I can’t figure it out what exactly.

const fetchFourSquareApi = (searchItem, center) => {
  var encodedURI = `https://api....`

  return HTTP.get(encodedURI, {}, function (error, response) {
    if (error) {
      console.log(error)
    }
    if (response.statusCode !== 200) {
      console.log(
        `Looks like there was a problem. Status Code: ${response.statusCode}`
      )
      return
    } else {
      console.log(response)
    }
    return response.data.response.venues
  })
}
export default fetchFourSquareApi

If you pass a callback function to HTTP, it becomes asynchronous, and won’t return anything itself.

If you are expecting the return response.data.response.venues to be returned as part of the HTTP call, it won’t happen. The HTTP call is asynchronous so, if you want to handle error/response in the callback, you will need to provide your own callback as well in your fetchFoursSquareApi parameters and then call that once you have your response.

If you want it to run synchronously, so the HTTP call blocks and waits until it gets the response, then you should remove the function(error,response) callback you have added.

Check the documentation on Meteor here:

Alternatively, you could refactor the code to use promises (as well as the code that is calling fetchFourSquareApi).

I’m doing vice-versa that is refactoring code from promises :slight_smile: to use HTTP meteor’s method.

Then you have the choice of either:

  • Using a callback (all the way up to where you want to process the results)
  • Using the HTTP without a callback so it will return the results

Here is a snippet I am using to call a rest-based SMS service:

	const response = HTTP.get(url+"send-sms.json",{
		auth:apikey+":"+secret,
		params: {
			from: "+xx43xxx2347",
			to: "+xx"+mobile,
			message: message,
		}
	});


The HTTP.get call blocks until the result comes back and I can process that on the next line - or return it to a caller of a function that wraps the above (which is what I actually do).