aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md2
-rw-r--r--src/ffi.js4
-rw-r--r--src/gleam/javascript/promise.gleam5
-rw-r--r--test/gleam/javascript/promise_test.gleam13
4 files changed, 23 insertions, 1 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 77f90e2..1ce8036 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,4 +8,4 @@
`to_list`, `from_list`, `map`, `fold`, `fold_right`, `get`, and `length`
functions.
- The `javascript/promise` module was created with the `Promise(value)` type and
- `resolve`, `tap`, `map_try`, `map`, `then_try` and `then` functions.
+ `rescue`, `resolve`, `tap`, `map_try`, `map`, `then_try` and `then` functions.
diff --git a/src/ffi.js b/src/ffi.js
index 450f5e3..d3ee8ce 100644
--- a/src/ffi.js
+++ b/src/ffi.js
@@ -94,3 +94,7 @@ export function map_promise(promise, fn) {
PromiseLayer.wrap(fn(PromiseLayer.unwrap(value)))
);
}
+
+export function rescue(promise, fn) {
+ return promise.catch((error) => fn(error));
+}
diff --git a/src/gleam/javascript/promise.gleam b/src/gleam/javascript/promise.gleam
index 8407c8c..3c7190c 100644
--- a/src/gleam/javascript/promise.gleam
+++ b/src/gleam/javascript/promise.gleam
@@ -1,3 +1,5 @@
+import gleam/dynamic.{Dynamic}
+
// TODO: docs
// TODO: labels
pub external type Promise(value)
@@ -5,6 +7,9 @@ pub external type Promise(value)
pub external fn resolve(value) -> Promise(value) =
"../../ffi.js" "resolve"
+pub external fn rescue(Promise(value), fn(Dynamic) -> value) -> Promise(value) =
+ "../../ffi.js" "rescue"
+
pub external fn then(Promise(a), fn(a) -> Promise(b)) -> Promise(b) =
"../../ffi.js" "then"
diff --git a/test/gleam/javascript/promise_test.gleam b/test/gleam/javascript/promise_test.gleam
index ea7c3d3..c77cd5a 100644
--- a/test/gleam/javascript/promise_test.gleam
+++ b/test/gleam/javascript/promise_test.gleam
@@ -71,3 +71,16 @@ pub fn then_try_error_test() -> Promise(Result(Int, Int)) {
|> promise.then_try(fn(a) { promise.resolve(Ok(a + 1)) })
|> promise.tap(fn(a) { assert Error(1) = a })
}
+
+pub fn rescue_healthy_test() {
+ promise.resolve(1)
+ |> promise.rescue(fn(_) { 100 })
+ |> promise.tap(fn(a) { assert 1 = a })
+}
+
+pub fn rescue_poisoned_test() {
+ promise.resolve(1)
+ |> promise.map(fn(_) { assert 1 = 2 })
+ |> promise.rescue(fn(_) { 100 })
+ |> promise.tap(fn(a) { assert 100 = a })
+}