jsrosetta

Bất đồng bộ

Promise

Promise .then()/.catch() và Promise.all() của Node.js so với channel (Go), Future (Rust), async/await (Swift) và CompletableFuture (Java).

Phiên bản tối thiểu
Node.js ≥ 12.20Go ≥ 1.25Rust ≥ 1.71Swift ≥ 5.7Java ≥ 25
Đã chạy thử trên
Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1

Code Node.js là ES module: lưu file .mjs hoặc đặt "type": "module" trong package.json.

Node.js có Promise sẵn trong ngôn ngữ. Go không có kiểu tương đương — cách gần nhất là dùng channel để nhận giá trị "đã settle" từ một goroutine chạy nền. Rust và Swift cũng không có kiểu Promise, nhưng có async/await để đạt cùng hiệu ứng (xem async/await nếu muốn ôn lại cú pháp đó). Java có CompletableFuture — kiểu gần với Promise nhất trong số năm ngôn ngữ, chuỗi được bằng .thenAccept()/.exceptionally() y hệt .then()/.catch(). Bài này dùng cú pháp .then()/.catch() cổ điển của Node.js.

Tạo một promise và xử lý kết quả (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));

Chạy nhiều promise song song (Promise.all)

Dùng lại asyncMethod và Result ở trên:

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

Tham khảo: github.com/miguelmota/golang-for-nodejs-developers#promises