fromPromise
fromPromise
takes a Promise and returns an object with 3 observable properties that track the status of the promise. The returned object has the following observable properties:
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.
The returned object implements PromiseLike<TValue>
, so you can chain additional Promise handlers using then
.
Note:
The status strings are available as constants:
mobxUtils.PENDING
,mobxUtils.REJECTED
,mobxUtils.FULFILLED
.
Observable promises can be created immediately in a certain state using fromPromise.reject(reason)
or fromPromise.resolve(value?)
. The main advantage of fromPromise.resolve(value)
over fromPromise(Promise.resolve(value))
is that the first synchronously starts in the desired state.
It is possible to directly create a promise using a resolve, reject function: fromPromise((resolve, reject) => setTimeout(() => resolve(true), 1000))
.
Parameters
promise
(IThenable<T>
): The promise which will be observed.
Return
IPromiseBasedObservable<T>
Examples
const fetchResult = fromPromise(fetch("http://someurl"))
// combine with when..
when(
() => fetchResult.state !== "pending"
() => {
console.log("Got ", fetchResult.value)
}
)
// 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:
const myComponent = observer(({ fetchResult }) =>
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)
)