Wait for response from http.request() (SOLVED)

In my code, I need the headers from a URL, so I use this:

location = ""
http.request(url, "HEAD", function(self, id, response)
   location = response.headers.location
end)

The code afterwards keeps going before the response arrives, so whenever I reference location outside of the callback function before it’s finished, I just get a blank string. If I do something like while location == "" do end after http.request(), it seems to also stop the callback function from running.

Yes, HTTP requests are asynchronous which means they take time to complete. The code will not stop on the http.request() line but instead immediately continue. That is why you have a callback function that gets invoked once the request has finished. If you need the location you either need to use it within the callback, send it as a message from the callback or synchronize using a coroutine.

4 Likes

Ughhhh, that was such an obvious solution. Thanks.

1 Like