Three states pending | | resolved | | rejected when in a pending state, can be transferred to resolved or rejected state When in the resolved state or rejected state, To be immutable, there must be a then asynchronous execution method, then takes two arguments and must return a promise: Prototype. Then = function(onResolved,onRejected){}Copy the code
function myPromise(callback) {
// Maintenance status
    this.status = 'pending'
// Store the callback function
    this.successArray = [];
    this.failArray = [];
// Define resolve and reject methods
    let resolve = (value) = > {
        // Change the state
        this.status = 'resolved';
        // Execute the callback function
        this.successArray.forEach(fn= > value = fn(value))
        // Clear the queue
        this.successArray = [];
        // Store the result
        this.value = value;
    }
    let reject = (value) = > {
        // Change the state
        this.status = 'resolved';
        // Execute the callback function
        this.failArray.forEach(fn= > value = fn(value))
        // Clear the queue
        this.failArray = [];
        // Store the result
        this.value = value;
    }
// Execute the callback function
    try {
        callback(resolve, reject);
    } catch(e) { reject(e); }}// Prototype method
myPromise.prototype.then = function (success, fail) {
// Determine the status
    if (this.status === 'pending') {
        // Store the callback function
        success && this.successArray.push(success);
        fail && this.failArray.push(fail);
    } else if (this.status === 'resolved') {
        // Execute immediately
        success && success(this.value)
    } else {
        fail && fail(this.value);
    }
    return this;
}
Copy the code