• Before encapsulating, we need to understand the basic process for using promises

    • First, a Promise is a class (constructor), because when we use it, we need new Promise().

    • Reject new Promise(resolve, reject)=>{})

    • Promise has three states, which are pending Rejected depressing

    • Promise status can only change once

      • pending= >rejected
      • pending= >fulfilled
    • Pomise’s Resolve Reject is used to change the Promise state

      • resolveChange the status to success
      • rejectChange the state to failed
    • What the then method does internally is determine the state and return data like that

let promise = new Promise((resolve,reject) = > {
    resolve('success')
    reject('failure')
})

promise.then(
    (value) = > {
        console.log(value)
    },
    (reason) = > {
        console.log(reason)
    }
)
Copy the code

Implement the base Promise

const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECT = 'reject'

class MyPromise {
    // An actuator used to receive external passes
    constructor(exctor) {
        exctor(this.resolve, this.reject)
    }

    // Current promise state
    status = PENDING

    // Record the promise success data
    value = null 

    // Record why the promise failed
    reason = null

    // The method of success
    resolve = (value) = > {
        if(this.status ! == PENDING)return
        this.status = FULFILLED
        this.value = value
    }

    // Fail method
    reject = (reason) = > {
        if(this.status ! == PENDING)return
        this.status = REJECT
        this.reason = reason
    }

    The then method is used to get promise data
    then (successCallback, failCallback) {
        if(this.status == FULFILLED) {
            successCallback(this.value)
        } else if (this.status == REJECT) {
            failCallback(this.reason)
        }
    }
}

const myPromise = new MyPromise((resolve, reject) = > {
    resolve('success')
    reject('failure')
})

myPromise.then((value) = > {
    console.log(value);
}, (reason) = > {
    console.log(reason);
})
Copy the code