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.
npm install futurable # or yarn add futurable or pnpm add futurable
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
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
}
The methods implemented, excluding those that are by nature static can be used:
They are the following:
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:
const controller = new AbortController();
const futurable = new Futurable((resolve, reject) => {
const data = /*..async operations or other..*/
resolve(data);
}, controller.signal);
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:
In addition is has:
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();
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
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
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 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
Takes a promise and transforms it into a futurable. Promise can be also a function that receives value from futurable chaining as parameter.
Example
const futurable = new Futurable((resolve, reject, utils) => {
utils.futurizable(new Promise(res => {
//asynchronous code
res(data);
}))
.then(val => resolve(val))
});
//...code
//OR
const futurable = new Futurable((res, rej) => {
// asynchornous code..
resolve(true);
});
//...code
futurable
.futurizable(/*promise to futurizable*/)
.then(val => .......);
//OR
futurable
.then(val => 3)
.futurizable((val /* val is 3 */) => new Promise(/*...*/) /*promise to futurizable*/, ..)
//...code
OnCancel static method. It accepts a callback or a object with cb property and an optional signal.
Example
const controller = new AbortController();
//...code
Futurable.onCancel({
cb: ()=>console.log("Cancelled"),
signal: controller.signal
});
//...code
Sleep static method. It accepts a timer or a object with timer property and an optional signal.
Example
//...code
Futurable.sleep({
timer: 3000,
signal: signal
});
//...code
Delay static method. It accepts a object with timer and cb properties and an optional signal property.
Example
const controller = new AbortController();
//...code
Futurable.delay({
cb: ()=>console.log("Cancelled"),
timer: 3000
});
//...code
Fetch static method.
Example
//...code
Futurable.fetch(/*url string..*/, {method: "POST"});
//...code
Futurizable static method.
Example
const controller = new AbortController();
//...code
Futurable.futurizable({promise: /*promise to futurizable*/, signal: controller.signal});
//...code
Extension of the static method all with cancellation support.
Example
const controller = new AbortController();
//...code
Futurable.all([
1,
Futurable.resolve(true, controlles.signal),
new Futurable/*...*/
], controller.signal);
//...code
controller.abort();
//OR
const f = Futurable.all([
1,
Futurable.resolve(true),
new Futurable/*...*/
]
//...code
f.cancel();
Extension of the static method allSettled with cancellation support.
Example
const controller = new AbortController();
//...code
Futurable.allSettled([
1,
Futurable.resolve(true, controller.signal),
new Futurable/*...*/
], controller.signal);
//...code
controller.abort();
//OR
const f = Futurable.allSettled([
1,
Futurable.resolve(true),
new Futurable/*...*/
];
//...code
f.cancel();
Extension of the static method any with cancellation support.
Example
const controller = new AbortController();
//...code
Futurable.any([
1,
Futurable.resolve(true, controller.signal),
new Futurable/*...*/
], controller.signal);
//...code
controller.abort();
//OR
const f = Futurable.any([
1,
Futurable.resolve(true, controller.signal),
new Futurable/*...*/
];
//...code
f.cancel();
Extension of the static method race with cancellation support.
Example
const controller = new AbortController();
//...code
Futurable.race([
1,
Futurable.resolve(true, controller.signal),
new Futurable/*...*/
], controller.signal);
//...code
controller.abort();
//OR
const f = Futurable.race([
1,
Futurable.resolve(true, controller.signal),
new Futurable/*...*/
];
//...code
f.cancel();
Creates a polling service with cancellation support and possibility to handle error. An optional param immediate can be set true if fun must to be invoke immediatly.
Example
//...code
const polling = Futurable.polling(() => Futurable.fetch(/*...*/)), {interval: 1000});
polling.catch(err => console.error(err));
//...code
polling.cancel();
Extension of static method withResolvers with support of cancel function and utils object of Futurable.
Example
//...code
const {promise, resolve, reject} = Futurable.withResolvers();
//...code
const result = await promise;
//...code
resolve("resolved");
Futurable is licensed under a MIT License.