JSFiddle - React, Tailwind, and code Playground
CSS
#h1 {
font-family: "Courier new";
}
JavaScript
const MyPromise = function(executionFunction){
this.promiseChain = [];
this.handleError = () => {};
this.onResolve = this.onResolve.bind(this);
this.onReject = this.onReject.bind(this);
executionFunction(this.onResolve, this.onReject);
};
MyPromise.prototype = {
constructor : MyPromise,
then(onResolve){
this.promiseChain.push(onResolve);
return this;
},
catch(handleError){
this.handleError = handleError;
return this;
},
onResolve(value){
let storedValue = value;
try {
this.promiseChain.forEach(function(nextFunction){
storedValue = nextFunction(storedValue);
});
}
catch (error){
this.promiseChain = [];
this.onReject(error);
}
},
onReject(error){
this.handleError(error);
}
};
const delay = function(t){
return new MyPromise(function(resolve, reject){
setTimeout(resolve, t);
});
};
const elem = document.getElementById('h1');
delay(1000)
.then(function(){
elem.innerHTML = '1';
return delay(2000);
})
.then(function(){
elem.innerHTML = '2';
});