value
: either the initial value, the value the Promise resolved to, or the value the Promise was rejected with. use.state
if you need to be able to tell the difference.state
: one of"pending"
,"fulfilled"
or"rejected"
And the following methods:
case({fulfilled, rejected, pending})
: maps over the result using the provided handlers, or returnsundefined
if a handler isn’t available for the current promise state.then((value: TValue) => TResult1 | PromiseLike<TResult1>, [(rejectReason: any) => any])
: chains additional handlers to the provided promise.
Note that the status strings are available as constants:
mobxUtils.PENDING
, mobxUtils.REJECTED
, mobxUtil.FULFILLED
- IThenable<T> The promise which will be observed
oldPromise
IThenable<T> ? The promise which will be observed
Examples
const fetchResult = fromPromise(fetch("http://someurl"))
// combine with when..
when(
() => fetchResult.state !== "pending",
() => {
}
)
// or a mobx-react component..
const myComponent = observer(({ fetchResult }) => {
switch(fetchResult.state) {
case "pending": return <div>Loading...</div>
case "rejected": return <div>Ooops... {fetchResult.value}</div>
case "fulfilled": return <div>Gotcha: {fetchResult.value}</div>
}
// or using the case method instead of switch:
fetchResult.case({
pending: () => <div>Loading...</div>,
rejected: error => <div>Ooops.. {error}</div>,
fulfilled: value => <div>Gotcha: {value}</div>,
}))
// chain additional handler(s) to the resolve/reject:
fetchResult.then(
(result) => doSomeTransformation(result),
(rejectReason) => console.error('fetchResult was rejected, reason: ' + rejectReason)
).then(
(transformedResult) => console.log('transformed fetchResult: ' + transformedResult)
)
Returns IPromiseBasedObservable<T>