https://github.com/sindresorhus/p-state
Inspect the state of a promise
https://github.com/sindresorhus/p-state
inspect introspection npm-package promise
Last synced: about 2 months ago
JSON representation
Inspect the state of a promise
- Host: GitHub
- URL: https://github.com/sindresorhus/p-state
- Owner: sindresorhus
- License: mit
- Created: 2020-11-22T11:25:34.000Z (about 5 years ago)
- Default Branch: main
- Last Pushed: 2024-03-16T18:43:38.000Z (over 1 year ago)
- Last Synced: 2025-03-28T21:25:41.407Z (8 months ago)
- Topics: inspect, introspection, npm-package, promise
- Language: JavaScript
- Homepage:
- Size: 25.4 KB
- Stars: 128
- Watchers: 3
- Forks: 7
- Open Issues: 1
-
Metadata Files:
- Readme: readme.md
- License: license
Awesome Lists containing this project
- promise-fun - p-state
README
# p-state
> Inspect the state of a promise
You would usually not need this as you can just `await` the promise at any time to get its value even after it's resolved. This package could be useful if you need to check the state of the promise before doing a heavy operation or for assertions when writing tests.
**Vote up [this issue](https://github.com/nodejs/node/issues/40054) if you want to see this feature being included in Node.js itself.**
## Install
```sh
npm install p-state
```
## Usage
```js
import timers from 'node:timers/promises';
import {promiseStateSync} from 'p-state';
const timeoutPromise = timers.setTimeout(100);
console.log(promiseStateSync(timeoutPromise));
//=> 'pending'
await timeoutPromise;
console.log(promiseStateSync(timeoutPromise));
//=> 'fulfilled'
```
## API
### `promiseStateAsync(promise: Promise)`
Asynchronously inspect the state of a promise.
Returns a promise for the state as a string with the possible values: `'pending'`, `'fulfilled'`, `'rejected'`.
Note: While this is async, it does return the state in the next [microtask](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide), which is almost right away.
```js
import timers from 'node:timers/promises';
import {promiseStateAsync} from 'p-state';
const timeoutPromise = timers.setTimeout(100);
console.log(await promiseStateAsync(timeoutPromise));
//=> 'pending'
await timeoutPromise;
console.log(await promiseStateAsync(timeoutPromise));
//=> 'fulfilled'
```
### `promiseStateSync(promise: Promise)`
Synchronously inspect the state of a promise.
Returns the state as a string with the possible values: `'pending'`, `'fulfilled'`, `'rejected'`.
Note: This method does not work in the browser.
## Related
- [p-reflect](https://github.com/sindresorhus/p-reflect) - Make a promise always fulfill with its actual fulfillment value or rejection reason
- [p-settle](https://github.com/sindresorhus/p-settle) - Settle promises concurrently and get their fulfillment value or rejection reason
- [More…](https://github.com/sindresorhus/promise-fun)