Answer#
The surface is similar: async function, await, and a way to wait for several things together. The difference that causes porting bugs is when work starts. A Promise is created by code that is already running, so the work is in flight when you hold the Promise. A Rust future is a description of work, and it is not started by being created.
| JavaScript | Rust | |
|---|---|---|
| Calling an async function | Runs to the first await now, returns a Promise | Returns a future; no code of the body has run |
| Starting the work | By the call | By .await or by tokio::spawn(fut) |
| Event loop | Built into the engine, single threaded | A runtime library you add; Tokio's default is multi-threaded |
| Wait for all | Promise.all([a, b]) | tokio::join!(a, b) |
| First one wins | Promise.race | tokio::select! |
| Errors | A rejected Promise, try/catch around await | Result as the output type, and ? after .await |
| Cancel | AbortController, by cooperation | Drop the future |
Node.js (v22.19.0):
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function work(name, ms) {
console.log(` ${name}: started`);
await sleep(ms);
console.log(` ${name}: done`);
return ms;
}
(async () => {
console.log("calling work(a)");
const p = work("a", 30); // runs until its first await right now
console.log("after the call");
console.log("result", await p);
let t = Date.now();
await work("b", 50); await work("c", 50);
const sequential = Date.now() - t;
t = Date.now();
const r = await Promise.all([work("d", 50), work("e", 50)]);
console.log("sums", r[0] + r[1], " sequential took >= 100 ms:", sequential >= 100, " Promise.all took < 100 ms:", Date.now() - t < 100);
})();calling work(a)
a: started
after the call
a: done
result 30
b: started
b: done
c: started
c: done
d: started
e: started
d: done
e: done
sums 100 sequential took >= 100 ms: true Promise.all took < 100 ms: trueThe Rust program (Tokio 1.54.1, features rt-multi-thread, macros, time) does the same, and prints a different line order at the start:
use std::time::Duration;
use tokio::time::sleep;
async fn work(name: &str, ms: u64) -> u32 {
println!(" {name}: started");
sleep(Duration::from_millis(ms)).await;
println!(" {name}: done");
ms as u32
}
#[tokio::main]
async fn main() {
println!("calling work(a)");
let fut = work("a", 30); // nothing has run yet: this is only a value describing the work
println!("after the call");
let r = fut.await; // it starts here
println!("result {r}");
let t = std::time::Instant::now();
let _ = work("b", 50).await;
let _ = work("c", 50).await;
let sequential = t.elapsed();
let t = std::time::Instant::now();
let (x, y) = tokio::join!(work("d", 50), work("e", 50));
let joined = t.elapsed();
println!("sums {} sequential took more than 100 ms: {} joined took less than 100 ms: {}", x + y, sequential.as_millis() >= 100, joined.as_millis() < 100);
}calling work(a)
after the call
a: started
a: done
result 30
b: started
b: done
c: started
c: done
d: started
e: started
e: done
d: done
sums 100 sequential took more than 100 ms: true joined took less than 100 ms: trueCompare the first three lines: JavaScript printed a: started before after the call, and Rust after. If your JavaScript depends on the side effect at the call ("start the request now, use it later"), the Rust port must either tokio::spawn the future at that point, or move the .await so that the work starts when the old code did. The order of the two "done" lines for d and e can differ from run to run; both programs completed the pair together in under 100 ms.
How to do it#
- Add Tokio (or another runtime) and
#[tokio::main]. - Port
async function f(): Promise<T>toasync fn f() -> T, or-> Result<T, E>where the Promise could reject. - Port
await ptop.await, andtry { await p } catchtomatch p.await { Ok(..) => .., Err(e) => .. }orp.await?. - Where the code starts work and awaits later, use
let handle = tokio::spawn(f()); ... handle.await. The spawned future must own its data ('static) and beSend; move orArcwhat it needs. - Port
Promise.alltojoin!, ortry_join!when the futures returnResultand you want the first error. - Do not block: no
std::thread::sleepor long loops inside async code; usespawn_blockingfor CPU work.
Common mistakes#
- Expecting an unawaited future to run. It never starts. The compiler warns about an unused future.
- Using a mutable variable from several spawned tasks. The borrow checker will refuse; share with
Arc<Mutex<T>>or send messages over a channel. - Assuming a single-threaded event loop. Tokio's default runtime runs tasks on several threads, so data shared between tasks must be thread safe.
Related questions#
Can Rust run the event loop on one thread like Node.js?#
Yes, Tokio has a current-thread runtime. It was not run for this thread.
What about C#'s async model?#
It also starts work at the call. See the thread comparing C# and Rust async.
Sources#
- The Rust Book, "Fundamentals of Asynchronous Programming": https://doc.rust-lang.org/book/ch17-00-async-await.html
- MDN, "async function": https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function