“This is the first day of my participation in the Gwen Challenge in November. See details of the event: The last Gwen Challenge in 2021”.

1. UnderstandPromise A+specification

The implementation of Promise needs to follow the standard specification of Promise A+, this specification tells us how to achieve A standard Promise, here is his official website we can go to see.

  • Promise A+Website:promisesaplus.com/

2. ImplementPromiseThe basic structure of

  • First let’s think about, how do we use onePromise.
    • PromiseIs a class that we need to usenewKeyword to call it,newaPromiseWe need to pass oneexecutorExecute the function,executorThe function takes two argumentsresolveFunction andrejectFunction.
    • PromiseThere are three states. The default ispendingState (we call this the wait state), callresolveFunction can makePromsieThe status of thependingintofulfilled(we call this a success state), callrejectFunction can makePromsieThe status of thependingintorejected(We call this a failed state).
    • let p = new Promise((resolve, reject) = > {
        resolve('success')})console.log(p);
      Copy the code
    • Console print result:
  • Implement basicPromisestructure
    • This time implements Promise’s directory structure

      1. P.js used to write about our case

      2. The index.js folder in the Promise folder is used to write our promise implementation. Age. TXT and name. TXT are the text files needed to write the case.

    • Basic architecture implementation

      1. We useclassTo implement thePromise
      2. We’re going to use variables to define three statesPENDING, depressing, REJECTEDCan prevent us from writing string errors later.
      3. innew PromiseWhen we pass inexecutorThe function,executorThe function needs to be executed immediately.
      4. performexecutorWe need to pass inresolveFunction andrejectfunction
      5. eachPromiseThere are three more properties,stateTo store thePromiseThe status of thevaluestorePromiseSuccess value,reasonstorePromiseThe reasons for the failure, which we’ll eventually derive, are inp.jsTo use it.
    • promise/index.js

          const PENDING = 'pending'
          const FULFILLED = 'fulfilled'
          const REJECTED = 'rejected'
      
          class Promise{
            constructor(executor){
      
              this.state = PENDING
              this.value = undefined
              this.reason = undefined
      
              const resolve = (value) = >{}const reject = (reason) = > {
      
              }
      
                executor(resolve,reject)
      
            }
      
            then(onFulfilled, onRejected){}}module.exports = Promise
      Copy the code

Subsequent articles will continue to be written every day