When the state changes, call the then callback to determine the pending state in the THEN method and do something -> save the callback function,
Add callback attribute: this.callack = {}
function Promise(executor){
// Resolve and reject are functions
// Add attributes
this.PromiseState = "pending";
this.PromiseResult = null
this.callack = {}
const self = this;
/ / resolve function
function resolve(data){
if(self.PromiseState ! = ='pending') return
// (1) Change the state of the object
// this.promisestate // This is window because resolve is called directly
self.PromiseState = 'fulfilled'
// (2) Set the object result value
self.PromiseResult = data
if(self.callback.onResolved){
self.callback.onResolved(self.PromiseResult)
}
}
/ / reject function
function reject(data){
if(self.PromiseState ! = ='pending') return
// (1) Change the state of the object
self.PromiseState = 'rejected'
// (2) Set the object result value
self.PromiseResult = data
if(self.callback.onRejected){
self.callback.onRejected(self.PromiseResult)
}
}
// Call the executor function synchronously
try {
executor(resolve,reject)
}catch(e){
reject(e)
}
}
// Add the then method
Promise.prototype.then = function(onResolved,onRejected){
if(this.PromiseState == 'fulfilled'){
onResolved(this.PromiseResult)
}
if(this.PromiseState == 'rejected'){
onRejected(this.PromiseResult)
}
// Determine pending status
if(this.PromiseState == 'pending') {// Save the callback function so that it can be called when the state changes
this.callack = {
onResolved:onResolved,
onRejected:onRejected
}
}
}
Copy the code