@extra-js/deferred
v0.1.1
Published
A simple wrapper around Promise API to programmatically trigger resolution or rejection
Downloads
5
Maintainers
Readme
Deferrable Promises (Deferred)
A simple promise-like object which exposes resolve
and reject
methods.
Resolve
import assert from 'assert';
import { Deferred } from '@extra-js/deferred';
process.on('unhandledRejection', (error) => {
throw error;
});
async function main() {
const future: Deferred<string> = new Deferred<string>();
setTimeout(future.resolve.bind(future, 'foo'));
const val = await future;
assert(val === 'foo', 'operation should be resolved');
}
main.call(this);
Reject
import assert from 'assert';
import { Deferred } from '@extra-js/deferred';
process.on('unhandledRejection', (error) => {
throw error;
});
async function main() {
const future: Deferred<string> = new Deferred<string>();
setTimeout(future.reject.bind(future, new Error('foo')));
try {
await future;
} catch (error) {
assert(error.message === 'foo');
}
}
main.call(this);
Timeout
import assert from 'assert';
import { Deferred } from '@extra-js/deferred';
process.on('unhandledRejection', (error) => {
throw error;
});
async function main() {
const TIMEOUT = 1000; // 1s
const future: Deferred<string> = new Deferred<string>(TIMEOUT);
try {
await future;
} catch (error) {
assert(error.message === 'Timeout');
}
}
main.call(this);