3 Mimic Rust's [`std::result`][result].
8 npm install rust-result
14 var fs = require('fs');
15 var Result = require('./');
18 // If you want async just get a promise or something.
19 var readFile = function (path, encoding) {
21 return Result.Ok(fs.readFileSync(path, encoding))
28 var result = readFile(__filename);
31 if (Result.isOk(result)) {
32 v = Result.Ok(result);
33 console.log('got ' + v.length + ' bytes')
35 else if (Result.isErr(result)) {
36 err = Result.Err(result);
37 console.error('oops!', err.message)
40 result = readFile(__filename + 'I do not exist')
41 if (Result.isOk(result)) {
43 console.log('got ' + v.length + ' bytes')
45 else if (Result.isErr(result)) {
46 err = Result.Err(result)
47 console.error('oops!', err.message)
58 type ErrResult<E <: Error> : {
63 Ok: ((T) => OkResult<T>) |
64 ((OkResult<T>) => T) |
65 ((ErrResult<E>) => void),
66 isOk: ((OkResult<T>) => true) |
67 ((ErrResult<E>) => false)
68 Err: ((E <: Error) => ErrResult<E>) |
69 ((ErrResult<E>) => E) |
70 ((OkResult<T>) => void),
71 isErr: ((ErrResult<E>) => true) |
72 ((OkResult<T>) => false)
78 The `Result.Ok` function is overloaded to do one of two things.
79 It can create a new `Ok` instance or it can check whether
80 the argument is an instance of `Ok`
82 If you call `Result.Ok` with a plain value it will return an
83 instance of `Ok` that boxes your plain value.
85 If you call `Result.Ok` with either an `Err` or an `Ok` instance
86 then it will return `undefined` for the `Err` and return the
87 value boxed in the `Ok`
91 The `Result.isOk` function just checks whether the argument
92 is an instance of `Ok`.
94 This predicate function returns true if you pass it an `Ok` and
95 returns false if you pass it an `Err`
99 The `Result.Err` function is overloaded to do one of two things.
100 It can create a new `Err` instance or it can check whether
101 the argument is an instance of `Err`
103 If you call `Result.Err` with a plain error it will return an
104 instance of `Err` that boxes your plain error.
106 If you call `Result.Err` with either an `Err` or an `Ok` instance
107 then it will return `undefined` for the `Ok` and return the
108 value err in the `Err`
112 The `Result.isErr` function just checks whether the argument
113 is an instance of `Err`.
115 This predicate function returns true if you pass it an `Err` and
116 returns false if you pass it an `Ok`
120 [result]: http://doc.rust-lang.org/std/result/