https://github.com/jcoreio/poll
yet another promise-based poller
https://github.com/jcoreio/poll
es2015
Last synced: 12 months ago
JSON representation
yet another promise-based poller
- Host: GitHub
- URL: https://github.com/jcoreio/poll
- Owner: jcoreio
- License: mit
- Created: 2017-12-18T20:16:18.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2024-10-03T16:51:21.000Z (over 1 year ago)
- Last Synced: 2024-11-10T02:14:55.238Z (over 1 year ago)
- Topics: es2015
- Language: TypeScript
- Size: 588 KB
- Stars: 1
- Watchers: 4
- Forks: 2
- Open Issues: 19
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# poll
[](https://travis-ci.org/jcoreio/poll)
[](https://codecov.io/gh/jcoreio/poll)
[](https://github.com/semantic-release/semantic-release)
[](http://commitizen.github.io/cz-cli/)
yet another promise-based poller (I didn't like the API design of others out there)
## Example
```sh
npm install --save @jcoreio/poll
```
```js
const poll = require('@jcoreio/poll')
const superagent = require('superagent')
poll(() => superagent.get('http://google.com'), 1000)
.timeout(30000)
.then(() => console.log("You're connected to the internet!"))
```
## `poll(fn, interval, [options])`
Begins calling `fn` every `interval` milliseconds until the condition passes
(which defaults to `fn` didn't throw an `Error` or return a rejected `Promise`).
Returns a `Promise` that resolves when polling finishes or fails, which may be:
- when `fn` calls the `pass` method provided to it
- when `fn` calls the `fail` method provided to it
- when `fn` returns/resolves to a value or throws/rejects with an `Error` that
passes the condition
- when a timeout is specified and `poll` times out waiting for any of the above
`fn` will be called with a context object:
```js
{
attemptNumber: number, // the number of this call (starting from 0)
elapsedTime: number, // the number of milliseconds since polling started
pass: (value: any) => void, // makes `poll` resolve immediately with this value
fail: (error: Error) => void, // makes `poll` reject immediately with this Error
}
```
You can change the condition by calling `.until` on the returned `Promise`:
```js
poll(...).until((error, result) => result > 3)
```
`error` will be the `Error` from the last call to `fn` (if it rejected or threw)
and `result` will be the value it resolved to or returned otherwise.
You can specify a timeout (in milliseconds) by calling `.timeout` on the returned `Promise`:
```js
poll(...).timeout(30000) // time out after 30 seconds
```
If you call `.noWrapError()` on the returned `Promise`, it won't wrap rejection errors.