最简单代码实现promise

Promise是一个对象,保存着未来将要结束的事件,它有两个特征:

1、对象的状态不受外部影响,Promise对象代表一个异步操作,有三种状态,pending进行中,fulfilled已成功,rejected已失败,只有异步操作的结果,才可以决定当前是哪一种状态,任何其他操作都无法改变这个状态,这也就是promise名字的由来

2、一旦状态改变,就不会再变,promise对象状态改变只有两种可能,从pending改到fulfilled或者从pending改到rejected,只要这两种情况发生,状态就凝固了,不会再改变,这个时候就称为定型resolved,

Promise的基本用法,

let promise1 = new Promise(function(resolve,reject){

setTimeout(function(){

resolve('ok')

},1000)

})

promise1.then(function success(val){

console.log(val)

})

最简单代码实现promise

class PromiseM {

constructor (process) {

this.status = 'pending'

this.msg = ''

process(this.resolve.bind(this), this.reject.bind(this))

return this

}

resolve (val) {

this.status = 'fulfilled'

this.msg = val

}

reject (err) {

this.status = 'rejected'

this.msg = err

}

then (fufilled, reject) {

if(this.status === 'fulfilled') {

fufilled(this.msg)

}

if(this.status === 'rejected') {

reject(this.msg)

}

}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章