see-promise-state
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

See Promise State

Adds synchronous state inspection to the native promise

Provides a function of the form:

<R>(p: Promise<R>) => PromiseWithState<R>

The returned stateful promise is the same object as the provided promise, with the following additional properties:

  • #resolved : boolean
  • #rejected : boolean
  • #complete : boolean

Useful for testing without introducting a mock for Promise. As such it is minorly limited; see caveats

Example

import assert from 'console';
import seePromiseState from 'see-promise-state';

const indefinite = seePromiseState(new Promise(() => {}));

assert(indefinite.complete === false);
assert(indefinite.resolved === false);
assert(indefinite.rejected === false);

const immediateResolution = seePromiseState(Promise.resolve());

assert(immediateResolution.complete === true);
assert(immediateResolution.resolved === true);
assert(immediateResolution.rejected === false);

const immediateRejection = seePromiseState(Promise.reject());

assert(immediateRejection.complete === true);
assert(immediateRejection.resolved === false);
assert(immediateRejection.rejected === true);

Caveats

Does not immediately apply to immediately resolving promises:

seePromiseState(Promise.resolve()).complete
// false

x = seePromiseState(Promise.resolve())
await sleep(0);
x.complete
// true

May not be correct for chains started before conversion

x = asyncTask();
x.then(() => console.log('A: ' + x.complete));
seePromiseState(x);
x.then(() => console.log('B: ' + x.complete));
await x;
// > 'A: false'
// > 'B: true'

Contributing

Feel free to make any contributions

The project uses yarn berry with zero-installs.

Build with: yarn build Test with: yarn test

If you use vscode, running yarn setupVSCode will setup vscode's typescript with yarn pnp.

If you use vscode launch configs are included for testing.

Readme

Keywords

none

Package Sidebar

Install

npm i see-promise-state

Weekly Downloads

2

Version

1.0.0

License

MIT

Unpacked Size

4.08 kB

Total Files

5

Last publish

Collaborators

  • normal-gaussian