Pendings

Better control of pending Promises
Pendings is a library for better control of single promise (or list of promises) by providing direct access resolve
/ reject
callbacks.
Installation
npm install pendings --save
Example
When working with Promises sometimes we need to store resolve
/ reject
callbacks for future fulfillment:
class MyClass {
waitSomeEvent() {
return new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
this.request();
});
}
onEvent(event) {
this.resolve(event.data);
}
onError(event) {
this.reject(event.data);
}
}
This library allows to reduce boilerplate code by automatically storing resolve
/ reject
callbacks:
const Pending = require('pendings').Pending;
class MyClass {
constructor() {
this.pending = new Pending();
}
waitSomeEvent() {
return this.pending.call(() => this.request());
}
onEvent(event) {
this.pending.resolve(event.data);
}
onError(event) {
this.pending.reject(event.data);
}
}
Moreover, it is useful when working with list of pending promises.
The unique id
is generated for each promise and allows to fulfill it later:
const Pendings = require('pendings');
class MyClass {
constructor() {
this.pendings = new Pendings();
}
sendDataAndWaitResponse(data) {
return this.pendings.add(id => {
data.id = id;
this.send(data);
});
}
onEvent(event) {
const data = event.data;
this.pendings.resolve(data.id, data);
}
onError(event) {
const data = event.data;
this.pendings.reject(data.id, data);
}
}
API
new Pendings(options)
Controls list of pending promises.
.add(fn, options)
.set(id, fn, options)
.has(id)
.resolve(id, value)
.reject(id, reason)
.rejectAll(reason)
.fulfill(id, value, reason)
.generateId()
new Pending()
Controls single pending promise.
.call(fn)
.resolve(value)
.reject(reason)
.fulfill(value, reason)
License
MIT @ Vitaliy Potapov