@alius/timeout-promise
v1.0.5
Published
Extended promise with timeout capability
Downloads
8
Readme
Extension of Promise class with timeout capability.
Installation
npm install @alius/timeout-promise
Usage
Constructor accepts two parameters (optional): executor and timeout.
import { TimeoutPromise } from "@alius/timeout-promise";
const tp = new TimeoutPromise((resolve, reject) => {
// for example connecting to database
}, 100);
// if connection was not acquired within 100ms - promise will be rejected
tp.then(
conn => {
console.log("connected");
}
).catch(
err => {
console.log("failed to connect");
}
);
You can defer executor function by creating new TimeoutPromise
and later provide executor function to execute()
.
import { TimeoutPromise } from "@alius/timeout-promise";
const tp = new TimeoutPromise();
tp.then(
value => {
console.log(`Got value ${value}`);
}
).catch(
err => {
console.log(`Got error ${err}`);
}
);
tp.execute((resolve, reject) => {
resolve("Defered executor completed");
});
You can use TimeoutPromise
as semaphore.
import { TimeoutPromise } from "@alius/timeout-promise";
const tp = new TimeoutPromise();
tp.then(
value => {
console.log(`Got value ${value}`);
},
err => {
console.log(`Got error ${err}`);
}
);
if (someCondition) {
tp.resolve("Ok");
} else {
tp.reject("Not ok");
}
API
Constructors
TimeoutPromise()
Creates new promise with defered execution.
TimeoutPromise(executor)
Creates normal promise.
TimeoutPromise(timeout)
Creates new promise with defered execution and timeout. If promise is not settled within specified amount of millisecons it will be rejected.
TimeoutPromise(executor, timeout)
Creates new promise with timeout. If promise is not settled within specified amount of millisecons it will be rejected.
Properties
state
Possible states:
- READY - executor function was not yet executed
- PENDING - executor function was executed but neither
resolve()
norreject()
has been called yet - LOCKED -
resolve()
was called with other thenable (other promise) and waiting for that thenable to resolve - FULFILLED - promise has been resolved
- REJECTED - promise has been rejected
settled
Returns true
if promise is either fulfulled or rejected
value
If promise has been resolved - value;
otherwise - undefined
error
If promise has been rejected - error;
otherwise - undefined
Methods
execute(executor)
Executes specified executor function. Function will be executed only if promise state is either READY or PENDING.
resolve(value)
Resolves promise with specified value if promise state is either READY or PENDING.
reject(err)
Rejects promise with specified error if promise state is either READY or PENDING.