I have found a custom js promise implementation and trying to understand it but I cant able to figure out how the callbacks are executed or triggered as definition of promise is called immediatly but we are only pushing into the callback array in then implementation
https://playcode.io/364624?tabs=script.js,preview,console
function myPromise(definitionFunction){
this.thenCallbacks = [];
this.status = 'pending';
this.value = undefined;
definitionFunction(resolver.bind(this),rejector.bind(this));
function resolver(value)
{
this.status = 'resolved';
this.value = value;
this.thenCallbacks.forEach(function(func){
console.log(func);
this.value = func(this.value);
},this);
}
function rejector(value)
{
}
}
myPromise.prototype.then = function(successCallback,errorCallback){
this.thenCallbacks.push(successCallback);
return this;
}
var test = new myPromise(function(resolve,reject){
var xhttp = new XMLHttpRequest();
var url = "https://jsonmock.hackerrank.com/api/stocks/search?page="+1;
xhttp.open("GET",url , true);
xhttp.onload = function() {
if (this.readyState == 4 && this.status == 200) {
resolve(this.responseText);
}
else
{
reject({
status: this.status,
statusText: xhttp.statusText
})
}
};
xhttp.onerror = function() {
reject({
status: this.status,
statusText: xhr.statusText
});
}
xhttp.send();
});
test.then((response)=>'kiran').then((resp)=>{return{name:'kiran'}}).then((resp)=>console.log(resp));
can some one clear this