当前位置:网站首页>Handwritten promise
Handwritten promise
2022-06-12 19:57:00 【Elegant pig】
Let's talk about the general idea first , Maybe not in this order , I also imitate Promise Basic use of , Just think of what to sum up , I think it should be Promise The core part is written .
1. establish MyPromise class
2. When instantiating, a function is passed in fn, And execute immediately
3. fn There are two parameters (resolve and reject), And they are all functions
4. Statement Promise The three states of are pending、fulfilled、rejected, And when instantiating, give the initial pending state
5. call resolve and reject When Change its state , call then Method , And pass the data to . When instantiating, give Promise An initial data result = null
6. then The formal parameters in the method are all asynchronous calls ,resolve and reject It is also the final execution , So using setTimeout
7. When exemplifying If an error occurs or an exception is thrown , You should catch exceptions call reject Method , So when instantiation is executed immediately use try catch
8. then Both parameters of a method must be functions , If the function passed in is not a function, we will give it an empty function
9. If resolve It is also asynchronous , In this case , perform then Method time , Judge status or pending, In this case, we need to add two arrays respectively The staging then Two methods in , Calling resolve And then go through the call . It's just a publish and subscribe
10. then Method can be called in chain , So we are then Method returns a handwritten MyPromise that will do
Here is the code :
class MyPromise {
static PENDING = 'pending'
static FULFILLED = 'fulfilled'
static REJECTED = 'rejected'
constructor(fn) {
this.status = MyPromise.PENDING
this.result = null
this.resolveCallbacks = []
this.rejectCallbacks = []
try {
fn(this.resolve.bind(this), this.reject.bind(this))
}catch(err) {
this.reject(err)
}
}
resolve(data) {
setTimeout(() => {
if(this.status == MyPromise.PENDING) {
this.status = MyPromise.FULFILLED
this.result = data
if(this.resolveCallbacks.length) {
this.resolveCallbacks.forEach(callback => {
callback(data)
})
}
}
})
}
reject(err) {
setTimeout(() => {
if(this.status == MyPromise.PENDING) {
this.status = MyPromise.REJECTED
this.result = err
if(this.rejectCallbacks.length) {
this.rejectCallbacks.forEach(callback => {
callback(err)
})
}
}
})
}
then(ONFULFILLED, ONREJECTED) {
return new MyPromise((resolve, reject) => {
ONFULFILLED = typeof ONFULFILLED === 'function' ? ONFULFILLED : () => {}
ONREJECTED = typeof ONREJECTED === 'function' ? ONREJECTED : () => {}
if(this.status == MyPromise.PENDING) {
this.resolveCallbacks.push(ONFULFILLED)
this.rejectCallbacks.push(ONREJECTED)
}
if(this.status == MyPromise.FULFILLED) {
setTimeout(() => {
ONFULFILLED(this.result)
})
}
if(this.status == MyPromise.REJECTED) {
setTimeout(() => {
ONREJECTED(this.result)
})
}
})
}
}A simple test
console.log('111111')
new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('resolve')
// reject('reject')
console.log(' Ha ha ha ')
})
}).then(data => {
console.log(data)
}, err => {
console.log(err)
})边栏推荐
猜你喜欢

进程会计、进程时间、守护进程

How to close icloud when Apple ID of Apple mobile phone forgets password and frequently jumps out to log in

Test prerequisites: recommend a special cross platform app performance test tool!

【生成对抗网络学习 其三】BiGAN论文阅读笔记及其原理理解

进程的创建fork()、消亡wait()

负数取余问题

Understand Jack Dorsey's web5 from the ppt on page 16

When will the index fail

sklearn中随机森林RandomForestClassifier的参数含义

First build green, then build city
随机推荐
设备管理-借还模块1
Reading small programs based on wechat e-book graduation design works (7) Interim inspection report
负数取余问题
Demand and business model analysis-1-business model canvas
Wechat e-book reading applet graduation design work (6) opening defense ppt
BigTable (II): how BigTable achieves scalability and high performance
Demand and business model innovation-5-process
Download and configuration of nuitka packaging tutorial
PostgreSQL database replication - background first-class citizen process walreceiver PG_ stat_ wal_ Receiver view
选电子工程被劝退,真的没前景了?
Microsoft Word tutorial, how to insert page numbers and table of contents in word?
Login to MySQL
Demand and business model innovation - demand 4- overview of demand acquisition
[digital ic/fpga] data accumulation output
Macro definitions and functions
The difference between MySQL full table scanning and indexing
The execution results of i+=2 and i++ i++ under synchronized are different
Software usage of Tencent cloud TDP virt viewer win client
EASYCODE one click plug-in custom template
Deep feature synthesis and genetic feature generation, comparison of two automatic feature generation strategies