upon-arrival
upon-arrival is a library that allows promised objects to be treated as if they were available synchronously for the purposes of calling their methods. This is very useful for libraries which may be lazy loaded, and have some side-effect that can occur sometime in the future, such as metrics gathering libraries noting that an event occurred.
The object returned by uponArrival
, the default export of this library, is an ES6 proxy. While the promise is not yet resolved, calls to functions on the target object are placed in a queue, which are then resolved in order when the target promise resolves. After the promise has resolved, calls to functions on the target object will be synchronous.
A simple example
import uponArrival from 'upon-arrival';
const myCallableObject = {
foo() {
return 'bar';
}
doBar() {
}
};
async function getCallable() {
await new Promise(resolve => setTimeout(resolve, 1000));
return myCallableObject;
}
const arrival = uponArrival(getCallable());
arrival.doBar();
const foo: string = arrival.foo();
Errors
upon-arrival exposes a promise that rejects when an error occurs. The type of the error is always ArrivalError
. Any causative error will appear in the cause
property of the error. If an error occurs as the promise is resolving, an error will be printed to the console with a stack trace.
An example with an error
import uponArrival, {PROMISE} from 'upon-arrival';
const arrival = uponArrival(myPromise);
const promise = arrival[PROMISE];
promise.catch(err => console.error(err.message));
arrival.methodThatThrows();
arrival.methodThatDoesNotExist();
API
function uponArrival<T>(promise: Promise<T>): Arrival<T>
(default export): Create an Arrival
object from a promise. An arrival object has all the same methods as the object returned by the promise, but they are all void
, since they cannot return anything if the promise hasn't been resolved yet. TODO: actually no reason to not return a promise that resolves with the value, once the inner promise is resolved.PROMISE
: A symbol that can be used to access the promise for error-handling.ArrivalError
: a subclass of Error
that is thrown when an error occurs while resolving the promise. It may have a cause
or errors
property which reference the cause of the error.
Further reading