How to use HTTPClient in HTML5?

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

In the official documentation there is an example on how to use this class. Part of the example contains this code:

# Wait until resolved and connected
while http.get_status() == HTTPClient.STATUS_CONNECTING or http.get_status() == HTTPClient.STATUS_RESOLVING:
    http.poll()
    print("Connecting..")
    OS.delay_msec(500)

However when I export such code to HTML5 and run it in a browser, I get the following error message in the Godot debugging console:

HTTPClient pooled multiple times in one frame, but request cannot progress more than once per frame on the HTML5 platform.

Further investigation allowed me to find that I should wait for frames instead of doing a delay, using this code:

yield(get_tree(), "idle_frame") 

But this is not always possible, especially when the script is in a utility class that isn’t meant to be added in a scene, thus is an Object and not a Node.

What’s the best strategy in such case?
I see that I can refactor my whole utility class to become a Node and add it to the scene just to have access to the SceneTree so I can wait for a frame, but it breaks the whole architecture and it makes dirty code, which I really want to avoid.

:bust_in_silhouette: Reply From: rojekabc

Hi.

I used last time HttpClient. Yes, in case of HTML5, you have to send one poll per frame, so I’ve created a Node, which is in the tree and replace all OS.delay to yield.

In place of HttpClient you may use HttpRequest node, which use HttpClient internally

:bust_in_silhouette: Reply From: eska

The scene tree is the main loop, so use

yield(Engine.get_main_loop(), 'idle_frame')

instead of yield(get_tree(), 'idle_frame').