@ndriadev/futurable
v2.3.1
Published
Extension Javascript's Promise API with more functionalities
Downloads
55
Maintainers
Readme
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:
- cancel
- onCancel
- sleep
- delay
- fetch
- futurizable
- Futurable.onCancel
- Futurable.sleep
- Futurable.delay
- Futurable.fetch
- Futurable.futurizable
- Futurable.all
- Futurable.allSettled
- Futurable.any
- Futurable.race
- Futurable.polling
- Futurable.withResolvers
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:
- 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);
- 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