10 lines of code to achieve a simple version of Promise

Before we implement it, let’s look at the call of Promise first.

 

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('Error ')
    }).then(function (img) {
        console.log(img.height)
        document.body.appendChild(img)
    })

Now we analyze and realize our promise.

First, Promise is a construction method, and when initialization, a function is passed as a parameter.

var MyPromise = function (doSomething) {
        this.doSomething = doSomething
    }

thenThe method clearly shows that it is an instance method of Promise and can be called in a chain, indicating that the Promise instance is returned in the then method, that is, this

MyPromise.prototype.after = function (resovle, reject) {
        this.doSomething(resovle, reject)
        return this
    }

The after method here is equivalent to the then method. Then the simplified version of MyPromise has been completed. His calling method is the same as that of an example.

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('Error ')
    }).after(function (img) {
        console.log(img.height)
        document.body.appendChild(img)
    })

 

Epilogue: compared to Promise, this implementation is too simple and functional is hardly worth mentioning. Just throw bricks into the jade.

Leave a Reply

Your email address will not be published. Required fields are marked *