Async operations and cancellation
English | 日本語
A script can wait without blocking the event loop. The API signature distinguishes automatic waiting from an explicit completion Signal.
Automatic waiting and explicit signals
GD.file.read_text(path) waits for the file operation and returns its result. GD.file.read_text_async(path) immediately supplies a Signal that you can combine with other operations and then await.
func main():
var pending: Signal = GD.file.read_text_async("message.txt")
var result: Array = await pending
var text: String = result[0]
var error: Err = result[1]
if error != null:
printerr(error.text())
return 1
print(text)
return 0See read_text and read_text_async for their exact return shapes.
Compose independent work
Pass independent operations as Callables so GD.async.all can subscribe before starting them. It preserves input order in the array of completion values. Each result keeps its own error; joining operations does not mean they all succeeded.
func main():
var results: Array = await GD.async.all([
GD.file.read_text_async.bind("first.txt"),
GD.file.read_text_async.bind("second.txt"),
])
for result: Array in results:
var error: Err = result[1]
if error != null:
printerr(error.text())
return 1
print(result[0])
return 0GD.async.spawn starts a cooperative routine on the main thread. It is not a worker-thread executor for CPU-heavy GDScript.
Use a cancellation context
GD.async.context creates a context. with_timeout creates a child with a deadline, measured in seconds; it does not change the parent. Parent cancellation propagates to children.
Pass the context first to GD.async.with_context_pair, then a two-result operation Signal. In a web handler, use req.context so work follows the request lifetime:
func load(req: GDWebRequest, db: GDDatabaseClient) -> Variant, Err:
return await GD.async.with_context_pair(req.context, db.query_async("SELECT 1"))Returning the result retains any operation or cancellation error for the handler's caller. Cancellation is distinct from cleanup: close streams and database row results that your code owns.
Avoid blocking work in callbacks
Keep route handlers and completion callbacks short. The _async variants of standard modules submit supported work to their managed executors. Awaiting a signal does not make an arbitrary synchronous loop nonblocking.