jsrosetta

Async

Promises

How Node.js's Promise .then()/.catch() and Promise.all() compare to channels (Go), Future (Rust), async/await (Swift), and CompletableFuture (Java).

Minimum versions
Node.js ≥ 12.20Go ≥ 1.25Rust ≥ 1.71Swift ≥ 5.7Java ≥ 25
Verified on
Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1

Node.js code is an ES module: save it as .mjs or set "type": "module" in package.json.

Node.js has Promise built into the language. Go has no equivalent type — the closest thing is using a channel to receive a "settled" value from a goroutine running in the background. Rust and Swift don't have a Promise type either, but they have async/await to get the same effect (see async/await for a refresher on that syntax). Java has CompletableFuture — the closest thing to a Promise among these five languages, chainable with .thenAccept()/.exceptionally() just like .then()/.catch(). This post uses Node's classic .then()/.catch() syntax.

Creating a promise and handling the result (then/catch)

function asyncMethod(value) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`resolved: ${value}`);
    }, 1000);
  });
}
 
asyncMethod("foo")
  .then((result) => console.log(result)) // → resolved: foo
  .catch((err) => console.error(err));

Running several promises in parallel (Promise.all)

Reusing asyncMethod and Result from above:

Promise.all([
  asyncMethod("A"),
  asyncMethod("B"),
  asyncMethod("C"),
])
  .then((results) => console.log(results)) // → ['resolved: A', 'resolved: B', 'resolved: C']
  .catch((err) => console.error(err));

Reference: github.com/miguelmota/golang-for-nodejs-developers#promises