10行代码实现简易版的Promise 实现之前,我们先看看Promise的调用
复制代码
const src = 'upload/201809041638407552.jpg?imageView&thumbnail=223x125&quality=100'
const promise = new Promise(function (resovle, reject) {
var img = document.createElement('img')
img.onload = function () {
resovle(img)
}
img.onerror = function () {
reject()
}
img.src = src
})
promise.then(function (img) {
console.log(img.width)
}, function () {
console.log('错误')
}).then(function (img) {
console.log(img.height)
document.body.appendChild(img)
})
复制代码
下面我们一边分析,一边实现自己的promise。
首先Promise是一个构造方法,并且初始化的时候传入了一个函数作为参数
复制代码
var MyPromise = function (doSomething) {
this.doSomething = doSomething
}
复制代码
then方法很明显可以看出是Promise的实例方法,并且可以实现链式调用,说明在then方法中返回了Promise实例,即this
复制代码
MyPromise.prototype.after = function (resovle, reject) {
this.doSomething(resovle, reject)
return this
}
复制代码
此处的after方法相当于then方法。那么MyPromise的简易版就完成了。他的调用方法和示例的调用是一样的。
复制代码
const src = 'upload/201809041638407552.jpg?imageView&thumbnail=223x125&quality=100'
const mypromise = new MyPromise(function (resovle, reject) {
var img = document.createElement('img')
img.onload = function () {
resovle(img)
}
img.onerror = function () {
reject()
}
img.src = src
})
mypromise.after(function (img) {
console.log(img.width)
}, function () {
console.log('错误')
}).after(function (img) {
console.log(img.height)
document.body.appendChild(img)
})
复制代码
后记:相比Promise,这个实现过于简单,功能上简直不值一提。仅仅抛砖引玉。https://www.cnblogs.com/linax/p/9570828.html