“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. ImplementPromise
The basic structure of
- First let’s think about, how do we use one
Promise
.Promise
Is a class that we need to usenew
Keyword to call it,new
aPromise
We need to pass oneexecutor
Execute the function,executor
The function takes two argumentsresolve
Function andreject
Function.Promise
There are three states. The default ispending
State (we call this the wait state), callresolve
Function can makePromsie
The status of thepending
intofulfilled
(we call this a success state), callreject
Function can makePromsie
The status of thepending
intorejected
(We call this a failed state).-
let p = new Promise((resolve, reject) = > { resolve('success')})console.log(p); Copy the code
- Console print result:
- Implement basic
Promise
structure-
This time implements Promise’s directory structure
-
P.js used to write about our case
-
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
- We use
class
To implement thePromise
- We’re going to use variables to define three states
PENDING, depressing, REJECTED
Can prevent us from writing string errors later. - in
new Promise
When we pass inexecutor
The function,executor
The function needs to be executed immediately. - perform
executor
We need to pass inresolve
Function andreject
function - each
Promise
There are three more properties,state
To store thePromise
The status of thevalue
storePromise
Success value,reason
storePromise
The reasons for the failure, which we’ll eventually derive, are inp.js
To use it.
- We use
-
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
-