avocado-old/packages/core/ticking-promise.js
2019-10-03 16:39:27 -05:00

50 lines
1.2 KiB
JavaScript

export class TickingPromise extends Promise {
constructor(executor, ticker) {
let _reject, _resolve;
super((resolve, reject) => {
_reject = reject;
_resolve = resolve;
if (executor) {
executor(resolve, reject);
}
});
this.executor = executor;
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);
})
}
}
if (0 === tickingPromises.length) {
return super.all(promises);
}
return new TickingPromise(
(resolve) => {
resolve(Promise.all(promises));
},
(elapsed) => {
for (let i = 0; i < tickingPromises.length; i++) {
tickingPromises[i].tick(elapsed);
}
},
);
}
tick(elapsed) {
this.ticker(elapsed, this.resolve, this.reject);
}
}