We need to understand the rationale for promises:
PromiseIs a class that, when executed, passes in an executor that executes immediatelyPromiseThere will be three kinds of state Pending, which is Fulfilled Fulfilled by the Rejected state`Pending --> Fulfilled`or`Pending --> Rejected`, and once it has changed, it cannot be modified twice;PromiseThe use of`resolve` 和 `reject`Two functions to change the state;`then`Method internal but the thing is state judgment: if the state is success, call the success callback if the state is failure, call the failure callback if it is`pending`State, will be`then`To execute the callbackCopy the code
Code implementation
The test of the HTML
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
<title>Document</title>
<script src="./myPromise.js"></script>
</head>
<body>
<script>
let myPromise = new MyPromise((resolve, reject) = > {
setTimeout(() = > {
resolve('success')},2000)
})
myPromise.then(
(value) = > {
console.log('resolve', value)
},
(reason) = > {
console.log('reject', reason)
}
)
</script>
</body>
</html>
Copy the code
The test of JS
const PENDING = 'PENDING'
const FULFILLED = 'fulfilled'
const REGEDTED = 'rejected'
class MyPromise {
constructor(executor) {
executor(this.resolve, this.reject)
}
status = PENDING
value = null
reason = null
onFulfilledCallback = null
onRejectedCallback = null
resolve = (value) = > {
if (this.status === PENDING) {
this.status = FULFILLED
this.value = value
this.onFulfilledCallback && this.onFulfilledCallback(value)
}
}
reject = (reason) = > {
if (this.status === PENDING) {
this.status = REGEDTED
this.reason = reason
this.onRejectedCallback && this.onRejectedCallback(reason)
}
}
then(onFulfilled, onRegected) {
if (this.status === FULFILLED) {
onFulfilled(this.value)
} else if (this.status === REGEDTED) {
onRegected(this.reason)
} else if (this.status === PENDING) {
this.onFulfilledCallback = onFulfilled
this.onRejectedCallback = onRegected
}
}
}
Copy the code
Reference article: juejin.cn/post/694531…