npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

until-promise

v0.3.0

Published

utility functions that poll until a condition is met

Downloads

478

Readme

A library that executes a function until its returned value satisfies some criteria.

Dependency Status Coverage Status Build Status

until-promise

until(aFunction, aConditionFunction, someOptions).then(...);

Supports 3 modes:

  • infinite: (no duration or retries option)
  • retries option (retries option)
  • duration option:=

In theory (...and in practice), you can combine retries and duration options.

To "throttle" the calls, you can pass wait option. The first call is done immediately. Then, if the condition is not satisfied, it waits waitms before executing the function a second time (...and so on...)

Usage

import until from 'until-promise';

until(
  // a function that takes no param
  // can return any value... such as a Promise..
  // `.bind(...)` as much a you want!
  () => { return aValue; },
  // a function that will be called with the returned/resolved value of the first function
  // and that should return true if the condition is satisfied
  (res) => { return res.prop === 'expectedValue'; },
  // optional options:
  {
    // * wait: number of milliseconds between 2 function calls
    wait: 500,
    // * duration: the maximum number of milliseconds before rejecting
    duration: 2000
    // * retries: maximum number of retries before rejecting
    retries: 3
  }
).then(() => {
  // do what you have to do
});

Setup / Reset

This library also expose a setup(options) function that allows to configure default options that will be used eveytime until is called (until setup(options) or reset() are called):

  • Promise: specify a Promise library like bluebird if needed (defaults to Promise which is available in nodejs and most modern browser)
  • onError: define a custom Error handler: its signature is:
// `reject` should be called exactly once.
onError({ errorType, reject, nbAttempts, startedAt, capturedResults }, options)
  • captureResults: if not falsy and > 0, until will cature the last X results and pass them to onError handler (capturedResults property)
  • wait: time to wait between 2 calls - default: 0
  • duration: max number of milliseconds before rejecting - default: Infinity
  • retries: default number of retries before rejecting - default: Infinity

Note that any of those options can also be used when invoking until(func, testFunc, options) (third param). Adding those options when invoking until will not modify the default until options

The default options are:

{
  wait: 0,
  captureResults: 0,
  Promise,
  onError({ errorType, reject, nbAttempts, startedAt, capturedResults }, options) {
    let err = new Error(`condition not satified after ${Date.now() - startedAt}ms / nbAttempts: ${nbAttempts}`);
    // note that you can attach properties to error if needed. For example:
    err.duration = Date.now() - startedAt;
    Object.assign(err, { nbAttempts, errorType, startedAt, capturedResults, options });
    reject(err);
  }
}

Gotcha

If the condition is never satisfied and duration is not a multiple of wait, then the returned promise might fail after Math.ceil(failAfter / wait) * wait ( which is > failAfter)

This will resolve after ~600ms:

let a = 1;
// `a` will equal 2 after 500ms
setTimeout(() => { a = 2; }, 500);
return until(
  function () { return Promise.resolve(a); },
  (res) => res === 2,
  // the function will be executed at:
  // ~0ms, ~200ms, ~400ms, ~600ms
  { wait: 200, duration: 1000 }
);

This is rejected after ~900ms:

let a = 1;
// `a` will equal to 2 after 5000ms
setTimeout(() => { a = 2; }, 5000);
return until(
  function () { return Promise.resolve(a); },
  (res) => res === 2,
  // the function will be executed at:
  // ~0ms, ~200ms, ~400ms and should fail at ~500ms (while waiting 200ms before doing the 4th call)
  { wait: 200, duration: 500 }

);

Custom Promise Library

Note

This library has no dependencies on bluebird. Just a dev dependency so I can test setup({ promise }) function.

If you want to use a custom Promise library (to benefit from some extra chaining methods exposed by this library for example...), use can use setup({ promise: customPromiseLibrary});

Here is an example with bluebird:

import until, {setup as untilSetup } from 'until-promise';
import bluebird as bluebird;

untilSetup({promise: bluebird});

return until(doSomething, conditionFunction)
  // `map` is available with bluebird, not with regular Promise
  .map(() => {...} );

Note: you don't have to call setup() in all the files that imports unitl-promise: any call to setup() from a js file will affect another file that also uses until-promise (in the same node process of course).

FYI: instead of using setup(), you can also wrap the until() call into a promiseLib.resolve(), like this:

return Bluebird.resolve(until(doSomething, conditionFunction)
  // `map()` is not a regular Promise method... yet...
  .map(() => {...} );

Dev Tips?Reminders

... Because I tend to forget things (and change way I do things between projects...)...

release new version

You got a green build for a branch, you merged that branch in master, master is clean... So:

  • npm version [major|minor|patch]