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

@ndriadev/futurable

v2.3.1

Published

Extension Javascript's Promise API with more functionalities

Downloads

55

Readme

npm version npm bundle size (scoped version) npm NPM

Statements Branches Functions Lines

Summary

Introduction

Futurable is a library that extends Javascript's Promise and Fetch APIs, adding a number of useful features and with support for Typescirpt. It can be used on both browser and node.

Often it happens where to develop a feature using promises that covers a particular need. Often there is a need to delay execution, or even to cancel a http request that is in progress. Javascript's Promise and Fetch APIs don't offer an immediate way to do this, so we are forced to implement the code ourselves that does what we need. The purpose of this library is to provide these features ready to use, without the user having to think about anything else.

:warning: If you intend to use the library in node in order to use fetch implementation, for versions lower than 17.5.0 it is necessary to install the node-fetch library, since the native support for the Fetch API was introduced by this version.

Installation


npm  install  futurable  # or yarn add futurable or pnpm add futurable

Usage

The library supports both ESM and CJS formats, so it can be used as follows:

import { Futurable } from '@ndriadev/futurable'; 		// ok

const { Futurable } = require('@ndriadev/futurable');	// ok

Use-case

React

Thanks to the use of this library, there is a simple and effective way to be able to cancel an Api request executed in a useEffect which, due to the Strict Mode, is executed twice:

Example

export default function Component() {
	//...code

	useEffect(() => {
        let f;
        function callApi() {
            f = Futurable
            .fetch("...")
            .then(resp => resp.json())
            .then(setTodo);
        }
        callApi();
        return () => {
            f && f.cancel();
        }
    },[])

	//OR

	useEffect(() => {
        const controller = new AbortController();
        Futurable
        .fetch(
            "...",
            {
                signal: controller.signal
            }
        )
        .then(resp => resp.json())
        .then(setTodo);

        return () => {
            controller.abort();
        }
    },[])

	//...code
}

API

The methods implemented, excluding those that are by nature static can be used:

  • During the construction of the futurable using the new operator;
  • In the chain-style promise chaining.

They are the following:

constructor(executor: FuturableExecutor, signal?: AbortSignal)

Futurable is instantiable like a classic Promise.

//Javascript Promise

const promise = new Promise((resolve, reject) => {
	const data = /*..async operations or other..*/
	resolve(data);
});

//Futurable
import { Futurable } from '@ndriadev/futurable';

const futurable = new Futurable((resolve, reject) => {
	const data = /*..async operations or other..*/
	resolve(data);
});

But it provides two more statements:

  1. Its constructor can receive a second parameter signal, an AbortSignal, usable to cancel the promise from the outside.
const controller = new AbortController();

const futurable = new Futurable((resolve, reject) => {
	const data = /*..async operations or other..*/
	resolve(data);
}, controller.signal);
  1. The executor function passed to the promise receives a third parameter, utils, optional.
const controller = new AbortController();

const futurable = new Futurable((resolve, reject, utils) => {
	const data = /*..async operations or other..*/
	resolve(data);
});

Utils is an object with the following properties which mirror the methods described in the usage section and which will be described below:

  • cancel;
  • onCancel:
  • delay;
  • sleep;
  • fetch;
  • futurizable.

In addition is has:

  • signal: internal futurable signal;

cancel(): void

If invoked, it cancel the futurable if it is to be executed or if it is still executing.

Example

function asynchronousOperation() {
	return new Futurable((res, rej) => {
		// asynchornous code..
		resolve(true);
	});
);

//...code

const futurable = asynchronousOperation();
	futurable.then(value => {
	//DO anything
});

//...code

futurable.cancel();

onCancel(cb: callback): void

If it is invoked, when the futurable is cancelled, it executes the callback passed as a parameter.

Example

const futurable = new Futurable((resolve, reject, utils) => {
	utils.onCancel(() => console.log("Futurable cancelled"));
	const data = /*..async operations or other..*/
	resolve(data);
});

//...code

futurable.cancel();

//OR

const futurable = new Futurable((res, rej) => {
	// asynchornous code..
	resolve(true);
});

//...code

futurable
.onCancel(() => console.log("Futurable cancelled"))
.then(val => .......);

//...code

futurable.cancel();
Output: Futurable cancelled

sleep(timer: number): Futurable

Waits for timer parameter (in milliseconds) before returning the value.

Example

const futurable = new Futurable((resolve, reject, utils) => {
	const data = /*..async operations or other..*/
	utils.sleep(3000);
	resolve(data);
});
//...code

//OR

const futurable = new Futurable((res, rej) => {
	// asynchornous code..
	resolve(true);
});

//...code

futurable
.sleep(3000)
.then(val => .......);

//...code

delay(cb: callback, timer: number)

Waits for timer parameter (in milliseconds), then executes callback with the futurable value and returns the result obtained from the invocation. Callback parameter, when delay is invoked as class method, has the value of futurable, like then method.

Example

const futurable = new Futurable((resolve, reject, utils) => {
	const data = /*..async operations or other..*/
	utils.delay(()=>console.log("delayed"), 3000);
	resolve(data);
});

//...code

//OR

const futurable = new Futurable((res, rej) => {
	// asynchornous code..
	resolve(true);
});

//...code

futurable
.delay((val)=> {
	console.log("delayed val", val);
	return val;
},3000)
.then(val => .......);

//...code

fetch(url: string | (val => string), opts: object | RequestInit)

Fetch API extension with cancellation support. Url parameter can be a string or a function with receive value from futurable chaining as paremeter.

Example

const futurable = new Futurable((resolve, reject, utils) => {
	utils.fetch(/*string url to fetch..*/)
	.then(val => resolve(val))
});

//...code

//OR

const futurable = new Futurable((res, rej) => {
	// asynchornous code..
	resolve(true);
});

//...code

futurable
.fetch(/*url to fetch..*/)
.then(val => .......);

//OR
futurable
.then(val => "https://...")
.fetch((val /* val came from previous then*/) => ..., ..)

//...code