FAQ - Help and questions

How do JavaScript promises and async functions compare with Rust futures?

#porting#javascript#asyncpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A JavaScript async function runs immediately, up to its first await, when you call it, and a Promise is a handle to work already in progress. A Rust async function returns a future that does nothing until it is awaited or spawned. Promise.all corresponds to tokio join, and Rust needs a runtime that you add.

Checked with rustc 1.93.0, tokio 1.54.1, Node.js v22.19.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

JavaScriptRust
Calling an async functionRuns to the first await now, returns a PromiseReturns a future; no code of the body has run
Starting the workBy the callBy .await or by tokio::spawn(fut)
Event loopBuilt into the engine, single threadedA runtime library you add; Tokio's default is multi-threaded
Wait for allPromise.all([a, b])tokio::join!(a, b)
First one winsPromise.racetokio::select!
ErrorsA rejected Promise, try/catch around awaitResult as the output type, and ? after .await
CancelAbortController, by cooperationDrop the future

Node.js (v22.19.0):

javascript
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);
})();
text
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: true

The Rust program (Tokio 1.54.1, features rt-multi-thread, macros, time) does the same, and prints a different line order at the start:

src/main.rsrust
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);
}
text
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: true

Compare 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#

  1. Add Tokio (or another runtime) and #[tokio::main].
  2. Port async function f(): Promise<T> to async fn f() -> T, or -> Result<T, E> where the Promise could reject.
  3. Port await p to p.await, and try { await p } catch to match p.await { Ok(..) => .., Err(e) => .. } or p.await?.
  4. 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 be Send; move or Arc what it needs.
  5. Port Promise.all to join!, or try_join! when the futures return Result and you want the first error.
  6. Do not block: no std::thread::sleep or long loops inside async code; use spawn_blocking for 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet