Write a Promise by hand
Promises primarily address the problem of callback hell. You can learn about promises by comparing them to, for example, how some HTTP requests would look if they were implemented with promises versus if they were written with callback functions. Here is a simple handwritten promise, let’s unveil the promise as it really is!
const PENDING = Symbol('pending')
const FULFILLED = Symbol('resolved')
const REJECTED = Symbol('reject')
function MyPromise(fn){
if(typeoffn! = ='function') {throw new Error('fn must be a function')}let state = PENDING
let value = null
let handler = {}
function resolve(result){
try{
state=FULFILLED
value=result
handler.onFulfill(value)
}catch(err){
reject(err)
}
}
function reject(error){
state=REJECTED;
value=error;
}
this.then=(onFulfill,onReject) = >{
switch(state){
case FULFILLED:onFulfill(value)
break
case REJECTED:onReject(value)
break
case PENDING:handler = { onFulfill,onReject }
}
}
fn(resolve,reject)
}
let p=new MyPromise((resolve,reject) = >{
setTimeout((a)= >{
console.log(3.' setTimeout ')
resolve('hello promise')},3000)})console.log(1,p)
p.then((val) = >{
console.log(4,val)
})
console.log(2.'ha ha')
Copy the code
The results
Related to the case
Sleep (3000). Then (()=>{console.log(‘…. ‘) ‘)}) Console. log is executed after 3s
Much like promise, I scribbled a way to implement it, and hope you can correct me or propose a better way to implement it
let sleep=function(ms){
let resolve=function(){
console.log('Ho ho ho')};let fn = function(){
setTimeout((a)= >{
resolve()
},ms)
return fn
}
Function.prototype.then=function(fun){
resolve=fun;
}
return fn();
}
sleep(3000).then((a)= >{console.log('Hahaha')})
Copy the code