JSFiddle - React, Tailwind, and code Playground
by alexb
TypeScript
class JonPromise<T> { // Generics PogChamp
boundToThen;
boundToCatch;
constructor(f) {
this.boundToThen = [];
this.boundToCatch = [];
const resolve = (someValue: T) => {
for (const f of this.boundToThen) {
f(someValue);
}
};
const reject = (someError: any) => {
for (const f of this.boundToCatch) {
f(someError);
}
}
f(resolve, reject);
}
// not sure if this is correct in typescript
then(f: (value: T) => any) {
this.boundToThen.push(f);
}
catch(f: (value: any) => any) {
this.boundToCatch.push(f);
}
}
// the creator of the promise provides a function that handles the special resolve/reject functions
const getSomeNumber = new JonPromise<number>(function(resolve, reject) {
setTimeout(() => {
resolve(Math.ceil(Math.random() * 10));
}, 2000); // <- happens 2 seconds in the future
// theres some weird inversion of control here make sure you understand it
// let me make sure it works before you decipher
});
getSomeNumber.then((value) => {
alert(`wow we got the number ${value}`)
})