Docs / Language Manual / Async & Promise
Edit

Async & Promise

ReScript's primary mechanism for async programming is the same as JavaScript's (callbacks and promises), since we compile cleanly to JavaScript and would like to avoid dragging in a heavy custom runtime.

There is currently no support for async and await keywords in ReScript; though our new Promise API bindings revamp + pipe will make your async code already look better than otherwise.

Promise (new)

Our up to date Promise bindings are currently not part of the the standard library. For now, please install them separately:

SH
npm install @ryyppy/rescript-promise --save

In your bsconfig.json:

JSON
{ "bs-dependencies": ["@ryyppy/rescript-promise"] }

Alternatively you may vendor the Promise.res / Promise.resi files files in your app codebase if you want to have more control.

You can find the APIs and full usage examples here.

Promise (legacy)

Note: The Js.Promise bindings are following the outdated data-last convention from a few years ago. We kept those APIs for backwards compatibility, so for now please use rescript-promise until we upstream the new bindings to our standard library.

ReScript has built-in support for JavaScript promises. The 3 functions you generally need are:

  • Js.Promise.resolve: 'a => Js.Promise.t('a)

  • Js.Promise.then_: ('a => Js.Promise.t('b), Js.Promise.t('a)) => Js.Promise.t('b)

  • Js.Promise.catch: (Js.Promise.error => Js.Promise.t('a), Js.Promise.t('a)) => Js.Promise.t('a)

Additionally, here's the type signature for creating a promise on the ReScript side:

RES
Js.Promise.make: ( ( ~resolve: (. 'a) => unit, ~reject: (. exn) => unit ) => unit ) => Js.Promise.t<'a>

This type signature means that make takes a callback that takes 2 named arguments, resolve and reject. Both arguments are themselves uncurried callbacks (with a dot). make returns the created promise.

Usage

Using the pipe operator:

ReScriptJS Output
let myPromise = Js.Promise.make((~resolve, ~reject) => resolve(. 2))

myPromise->Js.Promise.then_(value => {
  Js.log(value)
  Js.Promise.resolve(value + 2)
}, _)->Js.Promise.then_(value => {
  Js.log(value)
  Js.Promise.resolve(value + 3)
}, _)->Js.Promise.catch(err => {
  Js.log2("Failure!!", err)
  Js.Promise.resolve(-2)
}, _)