Giter Club home page Giter Club logo

promise-assist's Introduction

promise-assist

npm version Build Status

Several helper functions when working with native promises.

API

sleep

Useful for waiting a specific amount of time before continuing an operation.

import { sleep } from 'promise-assist';

async function myOperation() {
  const startTime = Date.now();
  await sleep(500);
  console.log(`${Date.now() - startTime}ms passed!`);
}

timeout

Useful for limiting the amount of time an async Promise-based operation can take.

import { timeout } from 'promise-assist';

async function myOperation() {
  try {
    const data = await timeout(
      fetchDataFromServer(), // pass a Promise to the timeout function
      10000, // request will be limited to 10 seconds
      `failed loading required data from backend`
    );
    // do something with the data
  } catch (e) {
    // handle errors
  }
}

deferred

Creates a deferred Promise, where resolve/reject are exposed to the place that holds the promise.

Generally a bad practice, but there are use-cases, such as mixing callback-based and Promise-based APIs, where this is helpful.

import { deferred } from 'promise-assist';

const { promise, resolve, reject } = deferred<string>();

// `resolve` or `reject` calls are reflected on `promise`
promise.then((value) => console.log(value));
resolve('some text');
// 'some text' is printed to console

retry

Executes provided action (sync or async) and returns its value. If action throws or rejects, it will retry execution several times before failing.

Defaults are:

  • 3 retries
  • no delay between retries
  • no timeout to stop trying

These can be customized via a second optional options parameter.

import { retry } from 'promise-assist';

// with default options
retry(() => fetch('http://some-url/asset.json'))
  .then((value) => value.json())
  .then(console.log)
  .catch((e) => console.error(e));

// with custom options
retry(() => fetch('http://some-url/asset.json'), {
  retries: Infinity, // infinite number of retries
  delay: 10 * 1000, // 10 seconds delay between retries
  timeout: 2 * 60 * 1000, // 2 minutes timeout to stop trying
})
  .then((value) => value.json())
  .then(console.log)
  .catch((e) => console.error(e));

waitFor

Same as retry, but with defaults that make more sense for tests:

  • delay: 10
  • timeout: 1000
  • retries: Infinity

It can be used to wait for some assertion to pass.

import { waitFor } from 'promise-assist';

describe('suit', () => {
  it('should wait for an assertion to pass', async () => {
    let trueLater = false;
    setTimeout(() => {
      trueLater = true;
    }, 50);

    await waitFor(() => {
      expect(trueLater).to.equal(true);
    });
  });
});

License

MIT

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.