Skip to content

Commit 156ad3c

Browse files
Use new internal async result methods
1 parent 26d84bc commit 156ad3c

File tree

1 file changed

+68
-26
lines changed

1 file changed

+68
-26
lines changed

_blogposts/2025-09-01-let-unwrap.mdx

Lines changed: 68 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,12 @@ date: "2025-09-01"
44
badge: roadmap
55
title: let?
66
description: |
7-
A new let-unwrap syntax just landed in ReScript.
7+
A new let-unwrap syntax just landed in ReScript. Experimental!
88
---
99

1010
After long discussions we finally decided on an unwrap syntax for both the `option` and `result` types that we are happy with and that still matches the explicitness of ReScript we all like.
1111

12-
# What is it exactly?
13-
14-
`let?` or `let-unwrap` is a tiny syntax that unwraps `result`/`option` values and *early-returns* on `Error`/`None`. It’s explicitly **experimental** and **disabled by default** behind a new “experimental features” gate.
15-
16-
### Example
12+
`let?` or `let-unwrap` is a tiny syntax that unwraps `result`/`option` values and *early-returns* on `Error`/`None`. It’s explicitly **experimental** and **disabled by default** behind a new "experimental features" gate. See below how to enable it.
1713

1814
Before showing off this new feauture, let's explore why it is useful. Consider a chain of `async` functions that are dependent on the result of the previous one. The naive way to write this in modern ReScript with `async`/`await` is to just `switch` on the results.
1915

@@ -35,26 +31,24 @@ let getUser = async id =>
3531

3632
Two observations:
3733
1. with every `switch` expression, this function gets nested deeper.
38-
2. The `Error` branch of every `switch` is just an identity mapper (neither wrapper nor contents change)
34+
2. The `Error` branch of every `switch` is just an identity mapper (neither wrapper nor contents change).
3935

40-
This means even though `async`/`await` syntax is available in ReScript for some time now, it is also understandable that people created their own `ResultPromise` libraries to handle such things with less lines of code, e.g.:
36+
The only alternative in ReScript was always to use some specialized methods:
4137

4238
```res
43-
module ResultPromise = {
44-
let flatMapOk = async (p: promise<'res>, f) =>
45-
switch await p {
46-
| Ok(x) => await f(x)
47-
| Error(_) as res => res
48-
}
49-
}
50-
5139
let getUserPromises = id =>
5240
fetchUser(id)
53-
->ResultPromise.flatMapOk(user => Promise.resolve(user->decodeUser))
54-
->ResultPromise.flatMapOk(decodedUser => ensureUserActive(decodedUser))
41+
->Result.flatMapOkAsync(user => Promise.resolve(user->decodeUser))
42+
->Result.flatMapOkAsync(decodedUser => ensureUserActive(decodedUser))
5543
```
5644

57-
While this is much shorter, it is also harder to understand because we have two wrapper types here, `promise` and `result`. And we have to wrap the non-async type in a `Promise.resolve` in order to stay on the same type level.
45+
**Note**: `Result.flatMapOkAsync` among some other async result helper functions are brand new in ReScript 12 as well!
46+
47+
This is arguably better, more concise, but also harder to understand because we have two wrapper types here, `promise` and `result`. And we have to wrap the non-async type in a `Promise.resolve` in order to stay on the same type level. Also we are giving up on our precious `async`/`await` syntax here.
48+
49+
## Introducing `let?`
50+
51+
Let's rewrite the above example again with our new syntax:
5852

5953
```rescript
6054
let getUser = async (id) => {
@@ -64,19 +58,67 @@ let getUser = async (id) => {
6458
Ok(decodedUser)
6559
}
6660
```
67-
With the new `let-unwrap` syntax, `let?` in short, we now have to follow the happy-path (in the scope of the function). And it's immediately clear that `fetchUser` is an `async` function while `decodeUser` is not. There is no nesting as the `Error` is automatically mapped. But be assured the error case is also handled as the type checker will complain when you don't handle the `Error` returned by the `getUser` function.
61+
62+
This strikes a balance between conciseness and simplicity that we really think fits ReScript well.
63+
64+
With `let?`, we can now safely focus on the the happy-path in the scope of the function. There is no nesting as the `Error` is automatically mapped. But be assured the error case is also handled as the type checker will complain when you don't handle the `Error` returned by the `getUser` function.
65+
66+
This desugars to a **sequence** of early-returns that you’d otherwise write by hand, so there’s **no extra runtime cost** and it plays nicely with `async/await` as the example above suggests.
67+
68+
Of course, it also works for `option` with `Some(...)`.
69+
70+
```rescript
71+
let getActiveUser = user => {
72+
let? Some(name) = activeUsers->Array.get(user)
73+
Some({name, active: true})
74+
}
75+
```
76+
77+
It also works with the unhappy path, with `Error(...)` or `None` as the main type and `Ok(...)` or `Some(...)` as the implicitly mapped types.
78+
79+
```rescript
80+
let getNoUser = user => {
81+
let? None = activeUsers->Array.get(user)
82+
Some("No user for you!")
83+
}
84+
85+
let decodeUserWithHumanReadableError = user => {
86+
let? Error(_e) = decodeUser(user)
87+
Error("This could not be decoded!")
88+
}
89+
```
90+
91+
Beware it targets built-ins only, namely `result` and `option`. Custom variants still need `switch`. And it is for block or local bindings only; top-level usage is rejected.
92+
93+
```rescript
94+
let? Ok(user) = await fetchUser("1")
95+
// ^^^^^^^ ERROR: `let?` is not allowed for top-level bindings.
96+
```
6897

6998
<!-- TODO: demonstrate error handling with polymorphic variants a little more -->
7099

71-
This desugars to a **sequence** of `switch`/early-returns that you’d otherwise write by hand, so there’s **no extra runtime cost** and it plays nicely with `async/await`. Same idea works for `option` with `Some(...)` (and the PR also extends support so the left pattern can be `Error(...)`/`None`, not just `Ok(...)`/`Some(...)`).
100+
### How to enable it
101+
102+
We have added an **experimental-features infrastructure** to the toolchain. If you use the new build system that comes with ReScript 12 by default, you can enable it in `rescript.json` like so:
103+
104+
```json
105+
{
106+
"experimental-features": {
107+
"letUnwrap": true
108+
}
109+
}
110+
```
72111

73-
Beware it targets built-ins only: `result` and `option`. (Custom variants still need `switch`.) And it is for block or local bindings only; top-level usage is rejected.
74-
Compiled JS code is the straightforward if/return form (i.e., “zero cost”).
112+
If you still use the legacy build system, enable it with the compiler flag `-enable-experimental`:
75113

76-
### How to enable it (experimental)
114+
```json
115+
{
116+
"compiler-flags": ["-enable-experimental", "LetUnwrap"]
117+
}
118+
```
77119

78-
We have added an **experimental-features infrastructure** to the toolchain. The corresponding compiler flag is `-enable-experimental`. This means you can enable `let?` in your `rescript.json`s `compiler-flags` and it forwards the feature to the compiler.
120+
We would love to hear your thoughts about this feature in the [forum](https://forum.rescript-lang.org/). Please try it out and tell us what you think!
79121

80-
This is purely a syntactical change so performance is not affected.
122+
Happy hacking!
81123

82124

0 commit comments

Comments
 (0)