使用 async
Working with async
到目前为止,我们一直只在处理同步用户界面:你提供一些输入,应用立即处理并更新界面。这很棒,但只是 Web 应用程序所做工作的一小部分。特别是,大多数 Web 应用必须处理某种异步数据加载,通常是从 API 加载某些内容。
So far we’ve only been working with synchronous user interfaces: You provide some input, the app immediately processes it and updates the interface. This is great, but is a tiny subset of what web applications do. In particular, most web apps have to deal with some kind of asynchronous data loading, usually loading something from an API.
由于“函数染色(function coloring)”问题,异步数据众所周知难以与代码中的同步部分集成。
Asynchronous data is notoriously hard to integrate with the synchronous parts of your code because of problems of “function coloring.”
在接下来的章节中,我们将看到一些用于处理异步数据的响应式原语。但在最开始有一点很重要:如果你只想做一些异步工作,Leptos 提供了一个跨平台的 spawn_local 函数,可以轻松运行 Future。如果本节其余部分讨论的原语似乎无法满足你的需求,请考虑将 spawn_local 与设置信号(signal)结合使用。
In the following chapters, we’ll see a few reactive primitives for working with async data. But it’s important to note at the very beginning: If you just want to do some asynchronous work, Leptos provides a cross-platform spawn_local function that makes it easy to run a Future. If one of the primitives discussed in the rest of this section doesn’t seem to do what you want, consider combining spawn_local with setting a signal.
虽然即将介绍的原语非常有用,在某些情况下甚至是必要的,但人们有时会遇到这样的情况:他们真的只需要派生(spawn)一个任务并等待它完成后再执行其他操作。在这些情况下,请使用 spawn_local!
While the primitives to come are very useful, and even necessary in some cases, people sometimes run into situations in which they really just need to spawn a task and wait for it to finish before doing something else. Use spawn_local in those situations!