Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/gleam/javascript/promise.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,26 @@ pub fn try_await(
})
}

/// Run a promise returning function on the value of a result, returning a
/// promise.
///
/// The function is only called if the value is `Ok`, and the returned promise
/// becomes the new value. If the result is `Error`, the error is returned
/// wrapped in a resolved promise.
///
/// This is a convenience function for when you have a synchronous `Result` and
/// want to chain into an asynchronous operation without first lifting the
/// result into a promise.
pub fn try_sync(
result: Result(a, b),
then: fn(a) -> Promise(Result(c, b)),
) -> Promise(Result(c, b)) {
case result {
Ok(value) -> then(value)
Error(reason) -> resolve(Error(reason))
}
}

/// Chain an asynchronous operation onto an array of promises, so it runs after the
/// promises have resolved.
///
Expand Down
24 changes: 24 additions & 0 deletions test/gleam/javascript/promise_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,30 @@ pub fn try_await_error_test() -> Promise(Result(Int, Int)) {
})
}

pub fn try_sync_ok_ok_test() -> Promise(Result(Int, Int)) {
Ok(1)
|> promise.try_sync(fn(a) { promise.resolve(Ok(a + 1)) })
|> promise.tap(fn(a) {
let assert Ok(2) = a
})
}

pub fn try_sync_ok_error_test() -> Promise(Result(Int, Int)) {
Ok(1)
|> promise.try_sync(fn(a) { promise.resolve(Error(a + 1)) })
|> promise.tap(fn(a) {
let assert Error(2) = a
})
}

pub fn try_sync_error_test() -> Promise(Result(Int, Int)) {
Error(1)
|> promise.try_sync(fn(a) { promise.resolve(Ok(a + 1)) })
|> promise.tap(fn(a) {
let assert Error(1) = a
})
}

pub fn rescue_healthy_test() {
promise.resolve(1)
|> promise.rescue(fn(_) { 100 })
Expand Down
Loading