Async
Stof runs async work the same way on every platform, including in a browser, on a single thread. Each piece of async work is a process, and the runtime switches between processes so they all make progress. Every call your app makes, and every #[main] and #[test] function, runs as a process too.
Async Functions and await
async fn (or #[async] on a function, which is the same thing) makes a function async: calling it starts a new process and gives back a promise right away. await waits for the result:
async fn load_rate() -> float {
sleep(10ms); // stand-in for slow work
0.2
}
#[main]
fn main() {
const rate = self.load_rate(); // a promise, returned immediately
pln(await rate);
}await works in any function, not just async ones. On a value that isn't a promise, it gives the value back as it is.
Doing Things in Parallel
Start several processes before awaiting any of them, and they run at the same time. await on a list waits for all of them:
async fn fetch_price(sku: str) -> float {
sleep(20ms);
sku == 'pro' ? 20 : 5
}
#[main]
fn main() {
// all three wait at the same time: about 20ms in total, not 60ms
const prices = await [self.fetch_price('pro'), self.fetch_price('team'), self.fetch_price('free')];
pln(prices);
}This is what makes Http.fetch fast in Stof: each request is its own process, so a document can start ten requests and await them together.
Async Calls and Blocks
async in front of any call runs it as a new process, even if the function isn't async itself. An async { ... } block runs its statements as a new process, and gives a promise for its last value:
fn add(a: int, b: int) -> int { a + b }
#[main]
fn main() {
const sum = async self.add(40, 2);
const product = async {
const v = 7;
v * 6
};
pln(await sum);
pln(await product);
}One catch: a block with a single expression, like async { 1 + 1 }, is read as a set, not a block. Write it as a statement: async { return 1 + 1; }.
An async { ... } block that isn't assigned to anything runs in the background, and the function carries on without waiting for it.
Collecting Work to Await Later
A common shape is starting work in a loop and awaiting it all at the end:
async fn notify(user: str) -> str {
sleep(5ms);
`notified ${user}`
}
#[main]
fn main() {
const pending = [];
for (const user in ['ada', 'grace', 'linus']) {
pending.push_back(self.notify(user));
}
for (const result in await pending) pln(result);
}How Processes Take Turns
Processes switch at loop iterations, function calls, await, and sleep. Code between those points runs without interruption, so a short calculation is never split in the middle. Two long loops in separate processes take turns, each making steady progress:
async fn count(label: str) -> str {
let n = 0;
for (const _ in 3) {
n += 1;
pln(`${label} ${n}`);
}
label
}
#[main]
fn main() {
await [self.count('a'), self.count('b')];
}That's also why tests that share data can interfere with each other: they run as processes on the same document. See Testing.
Async Functions from Your App
Your app can give a document async functions, like a database lookup or an API call, and the document awaits them like its own:
- TypeScript
- Python
- Rust
doc.lib('App', 'customer_plan', async (id: string) => (await db.customers.find(id)).plan, true);
# a regular function: the document's await gets its value
doc.lib('App', 'customer_plan', lambda id: db.customers.find(id).plan)
In Rust, App::customer_plan is a LibFunc with is_async: true, added with graph.insert_libfunc(..) (see Using Stof in Your App).
fn can_export(customer_id: str) -> bool {
const plan = await App::customer_plan(customer_id);
plan == 'pro'
}
Promise Types
Promise<T> is the type of a promise for a T. You rarely need to write it, since a promise is accepted wherever its result type is, but it's there for parameters and return types when you want to be explicit:
async fn total() -> int { 42 }
fn report(value: Promise<int>) -> str {
`total is ${await value}`
}
#[main]
fn main() {
pln(self.report(self.total()));
}Next, Testing.