Learn about our RFC process, Open RFC meetings & more.Join in the discussion! »

poll-until-promise

3.4.0 • Public • Published

Build Status Coverage Status NPM Version

Poll Until Promise

Wait until the executed promise resolved to a true value, Execute it every x milliseconds and stop after y milliseconds.

Install

npm install poll-until-promise

Usage

Fetching data

const { waitFor } = require('poll-until-promise');
 
waitFor(() => fetch('/get-data'), { interval: 100 })
    // Tries every 100ms (from the last failure)
    .then(value => console.log('Yey', value))
    .catch(err => console.error(err));
 

Waiting for something to be successful

const { waitFor } = require('poll-until-promise');
 
waitFor(() => {
  if (Math.random() >= 0.5) {
    throw new Error('try again');
  } else {
    console.log('all good')
  }
})
  .then(() => console.log('Yey'))
  .catch(err => console.error(err));

Using the class

const { PollUntil } = require('poll-until-promise');
 
const later = Date.now() + 1000; // 1 seconds into the future
 
let pollUntilPromise = new PollUntil();
pollUntilPromise
    .stopAfter(2 * 1000)    // Stop trying after 2 seconds
    .tryEvery(100)          // Tries every 100ms (from the last failure)
    .execute(() => {
        return new Promise((resolve, reject) => {
            if (+Date.now() >= later) {
                return resolve(true); // Some truthy value
            }
            reject(false);
        })
    })
    .then(value => console.log('Yey', value))
    .catch(err => console.error(err));
 

Options

const options = {
    interval: 100,
    timeout: 1000,
    stopOnFailure: false, // Ignores promise rejections
    verbose: false,
    message: 'Waiting for time to pass :)', // custom message to display on failure 
};
let pollUntilPromise = new PollUntil(options);

Methods

  • isResolved
pollUntilPromise.isResolved()
  • isWaiting
pollUntilPromise.isWaiting()
  • getPromise
pollUntilPromise.getPromise().then(() => console.log('OMG'))

Another Example - Static Function

const PollUntil = require('poll-until-promise');
const later = Date.now() + 1000; // 1 seconds into the future
 
let pollUntilPromise = new PollUntil();
pollUntilPromise
    .stopAfter(2 * 1000)
    .tryEvery(100)
    .execute(() => {
        if (+Date.now() >= later) {
            return true;
        }
        return false;
    })
    .then((value) => console.log('Yey', value))
    .catch((err) => console.error(err));
 

Used in AngularJs

An AngularJs compatible library based on poll-until-promise angular-wait-until.

Install

npm i poll-until-promise

DownloadsWeekly Downloads

272

Version

3.4.0

License

ISC

Unpacked Size

36.5 kB

Total Files

12

Last publish

Collaborators

  • avatar