Next: , Up: Fibers   [Contents][Index]


4.14.1 Fibers example

Running a fibers program is a little different than running a regular Scheme program. Fibers programs need to be invoked in an asychronous context from the host (usually JavaScript) and need to communicate the overall success or failure of the program back to the host.

To demonstrate, let’s make a very simple program that sleeps for one second before returning the value 42.

(use-modules (fibers promises)
             (fibers timers))

(lambda (resolved rejected)
  (call-with-async-result
   resolved rejected
   (lambda ()
     (display "Waiting... ")
     (force-output)
     (sleep 1)
     (display "done!\n")
     (force-output)
     42)))

Note that we’ve wrapped our program in a lambda that receives resolved and rejected arguments. When the Wasm host calls this procedure in an asynchronous manner, these arguments will be special host values that are used to resolve or reject the promise (see Promises) that represents the result of our program. The call-with-async-result procedure receives these host values and takes care of all the promise plumbing for us.

To try this out, save the above code to fibers-example.scm and run the following command:

guild compile-wasm --run --async fibers-test.scm

The expected output is:

Waiting... done!
(42)

There’s just one value returned but since Scheme supports multiple return values, the result of the program is a list of values.

To invoke an asynchronous procedure from JavaScript, use the call_async method on a Procedure object:

const [proc] = await Scheme.load_main("fibers-test.wasm");
proc.call_async();

Read on for the detailed fibers API reference.