opres - Operation Result
Rust-inspired std::result
object for JavaScript.
Usage
The idea is to return OperationResult
objects from places where you expect failures - database
calls, file I/O, remote APIs and so on. OperationResult
encapsulates success of the operation,
any data returned, and any errors that occurred along the way, allowing you to cleanly write your
failure-handling logic on top.
const OperationResult = ; const goodApiCall = { return 'my returned data';} const badApiCall = { return null 'something went wrong';} // later on in your calling code somewhereconst res1 = ; if res1ok console; else console; // You can also cause errors to throw using `expect()`. In this case an error would throw.const res2 = ;// However, `expect()` is a no-op for successful operations:const res3 = ;
You can also wrap a series of OperationResults as follows:
const OperationResult = ; const myFirstResult = ;const mySecondResult = ; const myOverallResult = OperationResult;
Other notes
Pattern matching
JavaScript can't really do any of the nice pattern matching stuff that Rust can do so that's not supported.
The closest you can get is an if statement as seen above:
if resok // successful else // not
You'll probably recognise the fetch-style .ok
.
Contributions
Pull requests are welcome.
Thanks
If this is useful for you let me know!