docs: explain asynchronous example ownership and callbacks

This commit is contained in:
2026-11-12 19:34:37 +08:00
parent 8a61d27938
commit a0545e7e40
6 changed files with 58 additions and 0 deletions
+9
View File
@@ -5,16 +5,21 @@ class TextFetcher {
output: TextBlock
problem: TextBlock
status: TextBlock
// 保存最新请求句柄,owner/key 替换后 apply 只读取当前任务;初始 Object 值尚不是可查询的 Task。
task: Object
// 完整响应留在 VM 业务字段,TextBlock 只显示提示;外部读取和 GUI 排版的内容量分开。
response: String
// 成功后取出完整 UTF-8 结果,写 response 供 Console 查询;provider 失败不会进入此方法。
function apply(self: TextFetcher): Unit {
// 成功交付前调度器已写入 Task 结果;绑定 self 的零参回调在所属 VM 执行,不在网络线程写业务字段。
self.response = self.task.result()
self.output.text = "请求完成;在 REPL 查看 fetcher.response"
}
// 同一 self/request 身份的新请求取消旧交付,重置旧内容并把显示绑定到新任务。
function fetch(self: TextFetcher, url: String): Unit {
// url 来自显式 fetch 调用,HTTP(S) GET 由后台 provider 完成;新句柄返回不代表网络已完成。
self.task = ui.fetchText(self, "request", url, self.apply)
// 同步清旧结果,避免新请求等待期间让 Console 把旧响应误认成新请求结果。
self.response = ""
self.output.text = ""
// 绑定读取当前 Task 方法,完成和失败由 worker 的任务状态变更传播。
@@ -24,9 +29,13 @@ class TextFetcher {
}
// 界面不自动访问网络,用户以 Console 明确指定 URL 后才创建任务。
output = TextBlock("尚未请求网络")
// 错误单独绑定 Task.error,即使失败没有调用 apply 也能展示原因。
problem = TextBlock("")
// 进度显示绑定任务状态,响应内容不拼接进这个控件,避免大正文参与每次布局。
status = TextBlock("")
// 全局业务入口让后续 REPL 复用同一 owner,因此多次 fetch 才会按 request 键替换。
fetcher = TextFetcher(output, problem, status, ui.state(0), "")
// Page 展示与任务身份分开,任务归属 fetcher;保持该业务对象可达时,页面隐藏不自动取消它。
page = Page()
page.title = "异步网络"
page.render(Column(24,16,TextBlock("在 REPL 调用 fetcher.fetch(HTTP 或 HTTPS 地址字符串)",2),status,problem,output))