How To Async Request on HTTPClient?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By hughes1992

Hello all, I’m wondering how to make async call requests that do not block the threads and execution of code in GDScript.

I’m making a plugin/addon that connects to my API server, however upon making the requests the whole game freezes and is not a proper feature in my opinion to have as part of my addon/plugin.

I’ve based my code on this from the docs:

I’ve seen other similar posts using low level threading nodes and using yield and resume however I can’t find any good resources on how to correctly make async requests without pausing the execution/threads.

There is this while loop that has the line yield(Engine.get_main_loop(), "idle_frame") which doesn’t seem to do anything different than not having it there.

while http.get_status() == HTTPClient.STATUS_REQUESTING:
    # Keep polling for as long as the request is being processed.
    if not OS.has_feature("web"):
        # Synchronous HTTP requests are not supported on the web,
        # so wait for the next main loop iteration.
        yield(Engine.get_main_loop(), "idle_frame")

I think the main issue are these while loops which is why I have a hunch that using a yield may be the best bet to get this fixed.

# Wait until resolved and connected.
while http.get_status() == HTTPClient.STATUS_CONNECTING or http.get_status() == HTTPClient.STATUS_RESOLVING:

If you have any reference code on how to do async/ non-blocking HTTPClient requests, please share it.

:bust_in_silhouette: Reply From: omggomb

There’s a node that does it, it’s called HTTPRequest. You just connect to request_completed signal and call request() on it. All the async stuff is handeled there.

The code you posted will only use yield when exporting for WebGL so that might be why it does not make any difference.

The connection stage of HTTPRequest.request() seems like synchronous.
In slow networks, on unreachable nodes etc., I have significant delays.

oleg.budin | 2020-02-14 18:34