Coroutines, Await & Async Execution

In Godot 3.x, asynchronous execution relied on the yield() keyword. In Godot 4.x / GDScript 2.0, asynchronous logic is powered by native await coroutines, mirroring modern Python and JavaScript async patterns.


🏛️ How Coroutines Work Under the Hood

When an executing function reaches an await statement, GDScript pauses the function execution, packs the current local variables into a GDScriptFunctionState / callable closure, and yields control back to the engine main loop.

When the awaited signal or timer fires, execution resumes on the exact line immediately following the await.


⚡ 1. Practical await Patterns

A. Waiting for a Timer (Non-blocking Delays)

func attack_with_cooldown() -> void:
    print("Attack executed!")
    # Wait 1.5 seconds without pausing the whole game or freezing the main thread
    await get_tree().create_timer(1.5).timeout
    print("Cooldown finished - ready to attack again!")

B. Waiting for Signals Across Nodes

func show_dialogue_and_wait() -> void:
    var dialogue_box: DialogueUI = $DialogueBox
    dialogue_box.display_text("Press space to continue...")
    
    # Pauses this function until the dialogue box emits dialogue_closed
    await dialogue_box.dialogue_closed
    
    print("Dialogue finished, resuming gameplay!")

C. Waiting for Asynchronous HTTP Requests

func fetch_online_leaderboard() -> void:
    var http_request := HTTPRequest.new()
    add_child(http_request)
    
    http_request.request("https://api.mygame.com/leaderboard")
    var response: Array = await http_request.request_completed
    
    # response = [result, response_code, headers, body]
    var json_string: String = response[3].get_string_from_utf8()
    print("Leaderboard: ", json_string)
    http_request.queue_free()

⚠️ 2. The Danger of Deadlocks with await

Awaiting Freed Nodes

If you await a signal from a node, but that node gets destroyed with queue_free() before emitting the signal, the coroutine will hang forever in memory, causing a silent coroutine leak.

Fix: Always ensure the target node remains valid or check is_instance_valid() before triggering dependencies.