Skip to content

Instantly share code, notes, and snippets.

@jpravetz
Created January 8, 2018 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpravetz/cd826dc0e20d58d7d06a1479898e87d3 to your computer and use it in GitHub Desktop.
Save jpravetz/cd826dc0e20d58d7d06a1479898e87d3 to your computer and use it in GitHub Desktop.
Promise wrapper, can be used in Node or in browser with transpiling
export class BusyPromise {
/**
* Promise wrapper that calls pre and post methods. Can be used to auto increment and decrement a
* counter, for example, or to indicate when busy and unbusy.
* @param opts {Object}
* @param [opts.pre] {Function} Function to execute before calling function
* @param [opts.onResolve] {Function} Function to execute after function resolves
* @param [opts.onReject] {Function} Function to execute if function rejects
* @param fn {function} Same as function in new Promise(fn)
*/
constructor (opts, fn) {
this.opts = opts;
this.opts.pre && this.opts.pre();
this.p = new Promise((resolve, reject) => {
fn((data) => {
this.opts.onResolve && this.opts.onResolve();
resolve(data);
}, (err) => {
this.opts.onReject && this.opts.onReject(err);
reject(err);
});
});
}
then (onResolve, onReject) {
return this.p.then(onResolve, onReject);
}
catch (onReject) {
return this.p.catch(onReject);
}
}
export class DemoView {
constructor() {
this.busy = 0;
this.busyOpts = {
pre: () => {
++this.busy;
},
onResolve: () => {
--this.busy;
},
onReject: (err) => {
--this.busy;
this.logger.error(err);
this.alert.error(err);
}
};
}
waitWithBusyFlag() {
return new BusyPromise(this.busyOpts, (resolve, reject) => {
return this.wait().then(resolve, reject);
});
}
wait() {
return new Promise((resolve) => {
setTimeout() => {
resolve();
}, 1000);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment