commit dc9f1fd329c0e4edf9c3eb1cde10109d07807d97
parent eb3a1fd5b3a2d838b0532c2d8f76699730548e1d
Author: ling0x <ling0x@users.noreply.github.com>
Date: Fri, 12 Jun 2026 11:35:06 +0100
coroutines
Diffstat:
1 file changed, 62 insertions(+), 0 deletions(-)
diff --git a/async_programming_in_rust/coroutines_promises_and_futures.js b/async_programming_in_rust/coroutines_promises_and_futures.js
@@ -0,0 +1,61 @@
+// Promises in JavaScript and futures and in Rust are two different implementations that are based on the same idea.
+//
+// Promises are one way to deal with the complexity that comes with
+// a callback-based approach.
+
+
+// Instead of:
+setTimer(200, () => {
+ setTimer(100, () => {
+ setTimer(50, () => {
+ console.log("I'm the last one");
+ });
+ });
+});
+
+// We can do:
+//
+// You see, promises return a State Machine that can be in one of
+// three states: Pending, Fullfilled, or Rejected.
+function timer(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+// This is referred to as the continuation-passing style.
+// Each subtask calls a new one once it's finished.
+timer(200)
+.then(() => timer(100))
+.then(() => timer(50))
+.then(() => console.log("I'm the last one"));
+
+// Coroutines and async/await
+//
+// - Async: the compiler rewrites what looks like a normal function
+// call into a `future` (in Rust) or a `promise` (in JavaScript).
+//
+// - Await, yields control to the runtime scheduler, and the task
+// is suspended until the future/promise you're awaiting
+// has finished.
+//
+// This way, we can write programs that handle concurrent operations
+// in almost the same way we write our normal sequential programs.
+//
+// You can consider the run function as a pausable task consisting
+// of several sub-tasks. On each "await" point, it yields control to the scheduler (in this case, it's the JavaScript event loop).
+//
+// Once one of the sub-tasks changes state to either `fullfilled` or
+// `rejected`, the task is scheduled to continue to the next step.
+async function run() {
+ await timer(200);
+ await timer(100);
+ await timer(50);
+ console.log("I'm the last one");
+}
+
+// In Rust, you can see the same transformation happening with the
+// function signature:
+//
+// From:
+// async fn run() -> () {...}
+//
+// To:
+// Fn run() -> impl Future<Output = ()>
+\ No newline at end of file