promise-holder
v1.0.2
Published
Better promise manipulation
Downloads
18
Readme
promise-holder
Overview
promise-holder
is a javascript/typescript package designed to simplify the handling of promises in your application. It provides a set of utilities and functions to streamline the creation, resolution, and rejection of promises, making asynchronous code management more efficient.
Installation
Install the package using npm:
npm install promise-holder
TL; DR
import PromiseHolder from 'promise-holder';
function waitTimeout() {
const promise = new PromiseHolder();
setTimeout(
() => {
// You can resolve you promise whenever you want
promise.resolve(123);
console.log('resolved');
},
100,
)
console.log('before await');
// Promise can be awaited like regular promise
const value = await promise;
console.log('awaited', value);
}
await waitTImeout();
// before await
// resolved
// awaited 123
API
new PromiseHolder()
To create a promise, simply instantiate PromiseHolder
class.
import PromiseHolder from 'promise-holder';
const promise = new PromiseHolder();
promise.then(onFulfilled, onRejected)
See Promise.then
documentation.
promise.catch(onRejected)
See Promise.catch
documentation.
promise.createdAt: date
Date at which the promise has been created
promise.resolve(value)
Callback to call to resolve the promise:
const promise = new PromiseHolder();
promise.resolve(123);
promise.then(
(value) => {
console.log(value); // 123
}
);
Notice: calling the resolve
method several more times will have no effect : only the first call will be resolved by the promise.
promise.reject(reason)
Callback to call to reject the promise:
const promise = new PromiseHolder();
const err = new Error('Promise rejected');
promise.reject(err);
promise.catch(
(err) => {
console.log(err.message); // Promise rejected
}
);
Notice: calling the reject
method several more times will have no effect : only the first call will be used as promise rejection reason.
promise.nodeCallback(err, value)
Use this method as node callback to resolve or reject the promise.
const PromiseHolder = require('promise-holder');
const fs = require('fs');
const promise = new PromiseHolder();
fs.readFile('myFile.txt', promise.nodeCallback);
promise.then(
(file) => {
console.log(file); // myFile.txt content
},
);
promise.onTime(timeout): Promise<boolean>
Return a promise that indicate if the promiseHolder has been resolved/rejected before the indicated duration:
- If the PromiseHolder has been resolved before the duration, then the promise resolve
true
. It will be resolved the moment the PromiseHolder has been fulfilled - If the PromiseHolder hasn't been resolved in time, the promise resolve
false
at the end of the duration.
const PromiseHolder = require('promise-holder');
const fs = require('fs');
const promise = new PromiseHolder();
promise.inTime(1000).then(
(inTime) => {
console.log('inTime', inTime); // inTime false
}
)