Better control of Promises
Pendings is a wrapping library over Promises providing flexible control of promise lifecycle.
It is useful for event-based code where you need to manually store resolve
/ reject
callbacks for later fulfillment.
It reduces boilerplate code and allows to split business logic from promise manipulation.
npm install pendings --save
- automatically store
resolve
/reject
callbacks for later fulfillment - automatically return existing promise for all calls until promise is fulfilled
- automatic reject promise after configured
timeout
- flexible manipulation with list of promises: dynamic insert and
waitAll()
method
Typical situation with promises in event-based code:
class Foo {
constructor() {
this.promise = null;
this.resolve = null;
this.reject = null;
}
asyncRequest() {
if (this.promise) { // if promise already exists - return it
return this.promise;
}
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
this.send();
});
return this.promise;
}
onSuccess(data) {
this.resolve(data);
}
}
Pending class allows to do it simpler:
const Pending = require('pendings').Pending;
class Foo {
constructor() {
this.pending = new Pending();
}
asyncRequest() {
return this.pending.call(() => this.send());
}
onSuccess(data) {
this.pending.resolve(data);
}
}
Pendings class is useful for dynamic list of promises.
Each promise gets unique id
(manually or auto-generated) and can be resolved later by that id.
const Pendings = require('pendings');
class Foo {
constructor() {
this.pendings = new Pendings();
}
asyncRequest() {
return this.pendings.add(id => {
this.send({id, foo: 'bar'}); // mark request with unique generated `id`
});
}
onSuccess(data) {
this.pendings.resolve(data.id, data); // resolve by `id`
}
onError(data) {
this.pendings.reject(data.id, data); // reject by `id`
}
}
{{>main}}
MIT @ Vitaliy Potapov