npm install rust-resultMimic Rust's [std::result][result].
``sh`
npm install rust-result
`js
var fs = require('fs');
var Result = require('./');
// If you want async just get a promise or something.
var readFile = function (path, encoding) {
try {
return Result.Ok(fs.readFileSync(path, encoding))
}
catch (ex) {
return Result.Err(ex)
}
}
var result = readFile(__filename);
var v, err;
if (Result.isOk(result)) {
v = Result.Ok(result);
console.log('got ' + v.length + ' bytes')
}
else if (Result.isErr(result)) {
err = Result.Err(result);
console.error('oops!', err.message)
}
result = readFile(__filename + 'I do not exist')
if (Result.isOk(result)) {
v = Result.Ok(result)
console.log('got ' + v.length + ' bytes')
}
else if (Result.isErr(result)) {
err = Result.Err(result)
console.error('oops!', err.message)
}
`
`jsig
type OkResult
v: T
}
type ErrResult
err: E
}
rust-result : {
Ok: ((T) => OkResult
((OkResult
((ErrResult
isOk: ((OkResult
((ErrResult
Err: ((E <: Error) => ErrResult
((ErrResult
((OkResult
isErr: ((ErrResult
((OkResult
}
`
The Result.Ok function is overloaded to do one of two things.Ok
It can create a new instance or it can check whetherOk
the argument is an instance of
If you call Result.Ok with a plain value it will return anOk
instance of that boxes your plain value.
If you call Result.Ok with either an Err or an Ok instanceundefined
then it will return for the Err and return theOk
value boxed in the
The Result.isOk function just checks whether the argumentOk
is an instance of .
This predicate function returns true if you pass it an Ok andErr
returns false if you pass it an
The Result.Err function is overloaded to do one of two things.Err
It can create a new instance or it can check whetherErr
the argument is an instance of
If you call Result.Err with a plain error it will return anErr
instance of that boxes your plain error.
If you call Result.Err with either an Err or an Ok instanceundefined
then it will return for the Ok and return theErr
value err in the
The Result.isErr function just checks whether the argumentErr
is an instance of .
This predicate function returns true if you pass it an Err andOk`
returns false if you pass it an
[result]: http://doc.rust-lang.org/std/result/