silphius/app/util/ticking-promise.js
2024-06-22 05:11:54 -05:00

53 lines
1.3 KiB
JavaScript

export default class TickingPromise extends Promise {
constructor(executor, ticker) {
let _reject;
let _resolve;
super((resolve, reject) => {
_reject = reject;
_resolve = resolve;
if (executor) {
executor(resolve, reject);
}
});
this.reject = _reject;
this.resolve = _resolve;
this.ticker = ticker;
}
static all(promises) {
const tickingPromises = [];
for (let i = 0; i < promises.length; i++) {
const promise = promises[i];
if (promise instanceof TickingPromise) {
tickingPromises.push(promise);
// After resolution, stop ticking the promise.
promise.then(() => {
tickingPromises.splice(tickingPromises.indexOf(promise), 1);
});
}
}
/* v8 ignore next 3 */
if (0 === tickingPromises.length) {
return super.all(promises);
}
return new TickingPromise(
(resolve, reject) => {
super.all(promises)
.then(resolve)
/* v8 ignore next */
.catch(reject);
},
(elapsed) => {
for (let i = 0; i < tickingPromises.length; i++) {
tickingPromises[i].tick(elapsed);
}
},
);
}
tick(elapsed) {
this.ticker(elapsed, this.resolve, this.reject);
}
}