JSFiddle - React, Tailwind, and code Playground
JavaScript
class MyPromise {
constructor(promised = () => {}) {
this.resolve = [];
this.reject = () => {};
promised(
(...args) => {
setTimeout(() => {
this.resolve.forEach((fn, i) => {
if (i === 0) this.result = fn(...args);
else this.result = fn(this.result);
});
}, 0);
},
(...args) => {
setTimeout(() => {
this.reject(...args);
}, 0);
}
);
}
then(resolveFunc, rejectFunc) {
this.resolve.push(resolveFunc);
this.reject = rejectFunc || this.reject;
return this;
}
}
const a = new MyPromise((resolve, reject) => {
if (true) { // Напишите false для случая с reject
resolve(1);
} else {
reject(0);
}
});
a.then(
(res) => {
console.log(res);
return res + 1;
},
(res) => {
console.log('REJECTED', res);
}
)
.then((res) => {
console.log(res);
return res * 2;
});