A Result, wrapped in a promise. The promise should never be rejected, and should always resolve to an Ok or Error.
For checking that a collection of computations all succeeded. Similar to Promise.all for Results.
Takes a list of Results. If all are Ok, collects the data in a list and returns ok([data]). If any are Errors, returns the first error(msg)
allOk([ok(1), ok(2), ok(3)]) // ok([1, 2, 3])
allOk([ok(1), error(2), error(3)]) // error(2)
For checking that a collection async computations all succeeded. Promise.all for Results wrapped in promises.
Takes a list of Promise
function countComments(postId) {
return pipeA
(fetchAllComments(postId)),
(allOkAsync),
(okThen(comments => comments.length))
(errorReplace("some comments didn't load"))
}
Call an action that could throw an error, and return a Result. Successful actions will be wrapped in an ok For predictable errors, you should provide a static or dynamic error handler
The unsafe action to perform
Takes a result, and runs either an onOk or onError function on it.
Result to match against
Function to run if the result is an Ok
Function to run if the result is an Error
The return value of the function that gets run.
// Use `either` to unwrap a Result.
const userId = either(
await fetchAUser(),
user => user.id,
() => null
)
// Use `either` to act on both cases, but leave wrapped.
const userId = either(
await fetchAUser(),
user => ok(user.id),
() => error("not found")
)
Wraps a message in an Error.
Runs a function for side effects on the payload, only if the result is Error.
the function to run on the error message
The original result
const result = fetchData();
// Log an error if the fetch failed.
errorDo(console.error)(result);
Runs a function for side effects on the payload, only if the result is Error. Waits for the side effect to complete before returning.
the function to run on the error message
a promise of the original Result
pipeA(
(fetchData)
// Logs an error, and awaits completion before moving on.
(errorDoAsync(logError))
(okThen(transformData))
Get the error message from a result. If it's an Ok instead, throw an error.
the error message
errorOrThrow(error("bad"));
// "bad"
errorOrThrow(ok("good"));
// throws new Error("good")
Replaces a message that's wrapped in an error(message)
Useful if you don't care about the old message, just the fact that previous call failed.
Takes a Result and a mapping function. If the result is an Error, applies the function to the message. If the result is an Ok, passes the Result through unchanged.
Attempts to rescue failed results. Passes successful ones through.
Takes a mapping function, then a result. If the result is an Error, applies the function to the data. If the result is an Ok, passes the Result through unchanged.
The return value must itself be a result, which will be returned.
the function to run on the error data
const rescueNotFound = errorThen(errorMessage =>
errorMessage === "not found" ? ok("unknown") : error(errorMessage)
);
rescueNotFound(ok("alice")) // ok("alice")
rescueNotFound(error("not found")) // ok("unknown")
rescueNotFound(error("network error")) // error("network error")
Chains together async operations that may succeed or fail
Takes a Result and a mapping function. If the result is an Error, applies the function to the data and returns the new promise-wrapped result. If the result is an Ok, passes the Result through unchanged.
the function to run on the error message
const fetchData = () => fetch("https://example.com/data");
pipeA
(getCachedData)
(errorRescueAsync(fetchData))
(okThen(transformData))
.value
Transforms a failed result, and passes through a successful result.
Takes a mapping function, then a result. If the result is an Error, applies the function to the data. If the result is an Ok, passes the Result through unchanged.
Wraps the output of the function in an Error.
the function to run on the error data
const normalizeErrorCase = errorThen(message =>
message.toLowerCase()
)
normalizeErrorCase(ok("alice")) // ok("alice")
normalizeErrorCase(error("NOT FOUND")) // error("not found")
Type guard to check if a Result is an Error
The result to check
const result = error("not found");
if (isError(result)) {
result.error // exists
}
Type guard to check if a Result is Ok
The result to check
const result = ok(1);
if (isOk(result)) {
result.ok // exists
}
Type guard to check if an object is a Result.
The object to check
const result = ;
isResult(error("not found")) // true
Wraps data in an Ok.
The success payload
ok(1)
Performs an operation that could succeed or fail on a successful result Passes through a failed result.
Takes a mapping function, then a result. If the result is an Ok, applies the function to the data. If the result is an Error, passes the Result through unchanged.
The return value must itself be a result, which will be returned.
the function to run on the ok data
Chains together async operations that may succeed or fail
Takes a Result and a mapping function. If the result is an Ok, applies the function to the data. If the result is an Error, passes the Result through unchanged.
the function to run on the ok data
pipeA
(fetchUser())
(okChainAsync(user => fetchComments(user.id)))
(okDo(comments => console.log('total comments:', comments.length))
.value
Runs a function for side effects on the payload, only if the result is Ok.
the function to run on the ok data
The original result
const result = fetchData();
// Log the data if the fetch succeeded.
okDo(console.log);
Runs a function for side effects on the payload, only if the result is Ok.
the async function to run on the ok data
A promise of the the original result
pipeA(
(fetchData)
// Saves to cache, and awaits completion before moving on.
(okDoAsync(saveToCache))
(okThen(transformData))
Get the error message from a result. If it's an Ok, throw an error.
the ok data
const okResult = ok("good");
okOrThrow(result);
// "good"
const errorResult = error("bad");
okOrThrow(result);
// throws new Error("bad")
Replaces a value that's wrapped in an {ok: data} Useful if you don't care about the data, just the fact that previous call succeeded.
Takes a Result and a mapping function. If the result is an Error, applies the function to the message. If the result is an Ok, passes the Result through unchanged.
It wraps the return value in an {error: new_message}.
Transforms a successful result, and passes through a failed result.
Takes a mapping function, then a result. If the result is an Ok, applies the function to the data. If the result is an Error, passes the Result through unchanged.
Wraps the output of the function in an Ok.
the function to run on the ok data
Safely parse JSON
Stringified JSON to parse
Awaits a promise, and returns a result based on the outcome
Note that the Error case isn't typesafe, since promises don't have an
error type, just a success one. It's probably a good idea to use a
errorThen
or errorReplace
to handle errors and soon as possible.
Ok if the promise resolved, Error if it was rejected.
pipeA(
(promiseToResult(fetch("http://example.com/data")))
(errorThen(handleError))
(okThen(transformData))
Converts a result to a boolean.
true if Ok, false if Error
resultToBoolean(ok(1)) // true
resultToBoolean(error(1)) // false
Converts a function that returns a promise to one that always resolved to a Result
Note that the Error case isn't typesafe, since promises don't have an
error type, just a success one. It's probably a good idea to use a
errorThen
or errorReplace
to handle errors and soon as possible.
A function that returns a promise
a function that returns a promise that always resolves to a Result
const writeFile = resultify(promisify(fs.writeFile));
pipeA(
(writeFile("path/to/file"))
(errorThen(handleError))
(okThen(transformFileData))
)
Generated using TypeDoc
Represents the result of an operation that could succeed or fail.