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

@marcelkloubert/promises

v3.0.2

Published

Helpers for promises, which work in Node and the browser.

Downloads

19

Readme

npm last build PRs Welcome

@marcelkloubert/promises

Helpers for promises, which work in Node and the browser.

Install

Execute the following command from your project folder, where your package.json file is stored:

npm i @marcelkloubert/promises

Usage

doRepeat(action: DoRepeatAction, countOrCondition: number | DoRepeatCondition, ...args: any[]): Promise

Repeats an action or promise.

import assert from "assert";
import { doRepeat, DoRepeatActionContext } from "@marcelkloubert/promises";

const repeatCount = 5979;
const counter = 0;

const results = await doRepeat(async (context: DoRepeatActionContext) => {
  console.log("context.state", String(context.state));
  context.state = context.index * 2;

  ++counter;

  // do some work here
}, repeatCount);

assert.strictEqual(results.length, repeatCount);
assert.strictEqual(counter, results.length);

isPromise(value: any): boolean

Checks if a value is a Promise.

import { isPromise } from "@marcelkloubert/promises";
import Bluebird from "bluebird";

// all are (true)
isPromise(Promise.resolve("Foo"));
isPromise(Bluebird.resolve("Foo"));
isPromise({
  then: (onfulfilled?: Function, onrejected?: Function): any => {},
  catch: (onrejected?: Function) => {},
});

// all are (false)
isPromise("Foo");
isPromise({
  then: (onfulfilled?: Function, onrejected?: Function): any => {},
});
isPromise(null);

isPromiseLike(value: any): boolean

Checks if a value is a PromiseLike.

import { isPromiseLike } from "@marcelkloubert/promises";
import Bluebird from "bluebird";

// all are (true)
isPromiseLike(Promise.resolve("Foo"));
isPromiseLike(Bluebird.resolve("Foo"));
isPromiseLike({
  then: (onfulfilled?: Function, onrejected?: Function): any => {},
});

// all are (false)
isPromiseLike("Foo");
isPromiseLike({});
isPromiseLike(null);

PromiseQueue

A promise queue.

import assert from "assert";
import { PromiseQueue } from "@marcelkloubert/promises";

// create and start the queue
const queue = new PromiseQueue({
  autoStart: true,
  concurrency: 10, // maximum 10 actions at the same time
});

const promises: Promise<any>[] = [];
let counter = 0;

// lets create 100 actions and
// add them to queue
const actionCount = 100;
for (let i = 0; i < actionCount; i++) {
  promises.push(
    queue.enqueue(async () => {
      // do some (long) work here ...

      ++counter;
    })
  );
}

// wait until all actions have been executed
await Promise.all(promises);

// stop the queue
queue.stop();

// counter should now be the number of
// enqueued actions
assert.strictEqual(counter, promises.length);

waitFor(action: WaitForAction, condition: WaitForCondition, ...args: any[]): Promise

Invokes an action or promise, but waits for a condition.

import {
  waitFor,
  WaitForActionContext,
  WaitForCondition,
} from "@marcelkloubert/promises";
import fs from "fs";

const waitForFile: WaitForCondition = async (context) => {
  // use context.cancel() function
  // to cancel the operation
  // maybe for a timeout

  // setup 'state' value for upcoming
  // action
  context.state = "Foo Bar BUZZ"; // (s. below in action)

  // return a truthy value to keep waiting
  // otherwise falsy to start execution of action
  return !fs.existsSync("/path/to/my/file.xlsx");
};

const result = await waitFor(async ({ state }: WaitForActionContext) => {
  // state === "Foo Bar BUZZ" (s. above)
}, waitForFile);

withCancellation(action: WithCancellationAction, ...args: any[]): Promise

Invokes an action or promise, which can be cancelled.

import {
  CancellationError,
  withCancellation,
  WithCancellationActionContext,
} from "@marcelkloubert/promises";

const promise = withCancellation(
  async (context: WithCancellationActionContext) => {
    let hasBeenFinished = false;
    while (!context.cancellationRequested && !hasBeenFinished) {
      // do some long work here
    }
  }
);

setTimeout(() => {
  promise.cancel("Promise action takes too long");
}, 10000);

try {
  await promise;
} catch (ex) {
  if (ex instanceof CancellationError) {
    // has been cancelled
  } else {
    // other error
  }
}

withRetries(action: WithRetriesAction, optionsOrMaxRetries: WithRetriesOptions | number, ...args: any[]): Promise

Invokes an action or promise and throws an error if a maximum number of tries has been reached.

import {
  MaximumTriesReachedError,
  withRetries,
} from "@marcelkloubert/promises";

const myAsyncAction = async () => {
  // do something here
};

try {
  // try this action
  await withTimeout(myAsyncAction, {
    maxRetries: 9, // try invoke the myLongAction
    // with a maximum of 10 times
    // (first invocation + maxRetries)
    waitBeforeRetry: 10000, // wait 10 seconds, before retry
  });
} catch (error) {
  // error should be a MaximumTriesReachedError instance
  console.error("Invokation of myLongAction failed", error);
}

withTimeout(action: WithTimeoutAction, timeout: number, ...args: any[]): Promise

Invokes an action or promise and throws an error on a timeout.

import { TimeoutError, withTimeout } from "@marcelkloubert/promises";

const action = () => {
  return new Promise<string>((resolve) => {
    setTimeout(() => result("FOO"), 1000);
  });
};

// submit action as function
// should NOT throw a TimeoutError
const fooResult1 = await withTimeout(action, 10000);

// submit action as Promise
// this should throw a TimeoutError
const fooResult2 = await withTimeout(action(), 100);

withWorker(workerFileOrUrl: string | URL, options?: WithWorkerOptions): Promise

Wraps the execution of a worker into a Promise.

import { withWorker } from "@marcelkloubert/promises";

// this is code for Node.js
// in a browser 'exitCode' will not exist
const { exitCode, lastMessage } = await withWorker("/path/to/worker_script.js");

Documentation

The API documentation can be found here.

License

MIT © Marcel Joachim Kloubert

Support

Or visit https://marcel.coffee/