10行代码实现简易版的Promise

实现之前,我们先看看Promise的调用

const src = 'https://img-ph-mirror.nosdn.127.net/sLP6rNBbQhy0OXFNYD9XIA==/799107458981776900.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 = 'https://img-ph-mirror.nosdn.127.net/sLP6rNBbQhy0OXFNYD9XIA==/799107458981776900.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,这个实现过于简单,功能上简直不值一提。仅仅抛砖引玉。

猜你喜欢

转载自www.cnblogs.com/linax/p/9570828.html