diff options
author | Louis Pilfold <louis@lpil.uk> | 2021-08-29 17:35:49 +0100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2021-08-29 17:35:49 +0100 |
commit | 6abcea012a67ab6b4eafc3401b0e1ca6a368e21a (patch) | |
tree | 7c4bdf3020030b9d66b906e077b0221d44c71c2d | |
parent | 9f9631eca11ab711c3b5f88b29a0024caca8ea62 (diff) | |
download | javascript-6abcea012a67ab6b4eafc3401b0e1ca6a368e21a.tar.gz javascript-6abcea012a67ab6b4eafc3401b0e1ca6a368e21a.zip |
Promise then_try
-rw-r--r-- | CHANGELOG.md | 2 | ||||
-rw-r--r-- | src/gleam/javascript/promise.gleam | 13 | ||||
-rw-r--r-- | test/gleam/javascript/promise_test.gleam | 18 |
3 files changed, 32 insertions, 1 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index e99cc60..77f90e2 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`, and `then` functions. + `resolve`, `tap`, `map_try`, `map`, `then_try` and `then` functions. diff --git a/src/gleam/javascript/promise.gleam b/src/gleam/javascript/promise.gleam index 7e3670a..8407c8c 100644 --- a/src/gleam/javascript/promise.gleam +++ b/src/gleam/javascript/promise.gleam @@ -31,3 +31,16 @@ pub fn map_try( } }) } + +pub fn then_try( + promise: Promise(Result(a, e)), + callback: fn(a) -> Promise(Result(b, e)), +) -> Promise(Result(b, e)) { + promise + |> then(fn(result) { + case result { + Ok(a) -> callback(a) + Error(e) -> resolve(Error(e)) + } + }) +} diff --git a/test/gleam/javascript/promise_test.gleam b/test/gleam/javascript/promise_test.gleam index 9d37984..ea7c3d3 100644 --- a/test/gleam/javascript/promise_test.gleam +++ b/test/gleam/javascript/promise_test.gleam @@ -53,3 +53,21 @@ pub fn map_try_error_test() -> Promise(Result(Int, Int)) { |> promise.map_try(fn(a) { Ok(a + 1) }) |> promise.tap(fn(a) { assert Error(1) = a }) } + +pub fn then_try_ok_ok_test() -> Promise(Result(Int, Int)) { + promise.resolve(Ok(1)) + |> promise.then_try(fn(a) { promise.resolve(Ok(a + 1)) }) + |> promise.tap(fn(a) { assert Ok(2) = a }) +} + +pub fn then_try_ok_error_test() -> Promise(Result(Int, Int)) { + promise.resolve(Ok(1)) + |> promise.then_try(fn(a) { promise.resolve(Error(a + 1)) }) + |> promise.tap(fn(a) { assert Error(2) = a }) +} + +pub fn then_try_error_test() -> Promise(Result(Int, Int)) { + promise.resolve(Error(1)) + |> promise.then_try(fn(a) { promise.resolve(Ok(a + 1)) }) + |> promise.tap(fn(a) { assert Error(1) = a }) +} |