10 lines of code to realize the simple version of Promise

Keywords: Javascript

Before implementation, let's take a look at the call to 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('error')
    }).then(function (img) {
        console.log(img.height)
        document.body.appendChild(img)
    })

Let's analyze and implement our own promise.

First, Promise is a constructor, and a function is passed in as a parameter during initialization

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

The then method is obviously the instance method of Promise, and can realize chain call, indicating that 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. So the simple version of MyPromise is finished. His calling method is the same as that of the 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)
    })

 

Postscript: compared with Promise, the implementation is too simple and the function is not worth mentioning. Just throw a brick and draw a jade.

Posted by Locust on Mon, 06 Jan 2020 06:04:26 -0800