title | description | canonical |
---|---|---|
Async & Promise | JS Promise handling in ReScript | /docs/manual/latest/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.
However, it is planned for us to introduce a coroutine-like feature in the future; for that reason, we're postponing introducing the keywords async
and await
into the language; though our (upcoming) Promise API bindings revamp + pipe will make your async code already look better than otherwise.
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:
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.
Using the pipe operator:
<CodeTab labels={["ReScript", "JS Output"]}>
letmyPromise=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) }, _)
varmyPromise=newPromise(function(resolve,reject){returnresolve(2);});myPromise.then(function(value){console.log(value);returnPromise.resolve((value+2)|0);}).then(function(value){console.log(value);returnPromise.resolve((value+3)|0);}).catch(function(err){console.log("Failure!!",err);returnPromise.resolve(-2);});