Three lines of code to implement a simple version of promise

Time:2020-7-5

preface

As a student from the back end, I was tossed about by various “anti human” concepts in JS
One of the most impressive is promise, which is really hard to understand… So I have the idea of writing a simple promise
Hope to help some new students like me who feel that promise is difficult to understand

Promise’s tutorials are numerous on the Internet, among which the most easy to understand is Ruan Yifeng’s ES6
So today, we will not repeat how to use promise. Today, we will learn from another perspective,
Make a wheel by yourselfBack to hellThe problem of

Simple implementation

Look at the code

function easyPromise (fn) {
    this.then = cb => this.cb = cb
    this.resolve = data => this.cb(data)
    fn(this.resolve)
}

Detailed explanation

The above code implements a simple “promise” to implement the then callback. In order to reduce the amount of code, the abbreviation of ES6 is used. The actual deployment should be like this

function easyPromise (fn) {
    var that = this

    //The first step is to define then ()
    this.then = function (cb) {
        //Save the parameters (callback functions) in the brackets of then () first
        that.cb = cb
    }

    //Define a resolve
    this.resolve = function(data) {
        that.cb(data)
    }

    //Pass resolve as a callback function to FN
    fn(this.resolve)
}

Now let’s look at how to use it

new easyPromise((resolve) => {
    setTimeout(() => {
        Resolve
    }, 1000)
}).then((data) => {
    console.log(data)
})

Results: after 1 second, the console outputDelay execution

Also in order to facilitate understanding, we might as well write the above code to understand a bit

//Define a function to pass to promise, which receives a function (resolve) as an argument.
//The function of resolve is to inform promise that the callback function in then should be executed at an appropriate time.
function promiseCallback (resolve) {
   setTimeout(() => {
      Resolve
   }, 1000)
}

//Define a callback function to be passed to then
function thenCallback (data) {
    console.log(data)
}

//Instantiate promis and pass in the corresponding callback respectively
new easyPromise(promiseCallback)
.then(thenCallback)

tips: promise.then()The callback function in brackets is not executed immediately, but saved

Let’s sort out the execution process

  1. Pass firstthenholdthenCallbackSave it

    this.then = function (cb) {
      that.cb = cb
    }

    therecbThis is the example abovethenCallbackSo it can be equivalent to this.cb = thenCallback

  2. implementpromiseThe function in brackets, and define the function in advanceresolveThe function is passed to him as an argument

    fn(this.resolve)

    therefnThis is the example abovepromiseCallback

  3. implementpromiseCallbackOur logic jumps topromiseCallbackFunction internal

    setTimeout(() => {
      Resolve
    }, 1000)

    The logic is very simple, that is, wait for 1 second and executeresolveFunction, this oneresolveWhere did it come from?

    fn(this.resolve) -> promiseCallback (resolve) -> resolve

  4. implementresolveOur logic jumps toresolveFunction internal

    that.cb(data)

    thisthat.cbWhere did it come from? It is the callback function in the then bracket that we saved in the first step, that isthenCallback

    console.log(data)

    So it will output in one secondDelay execution

last

Well, that’s itpromiseOf course, there are many functions not implemented, but the purpose of this paper is to help novices better understandpromise,
Not to implement a complete, compliantpromise A+canonicalpromiseTo learn more about children’s shoes, here are some links

  1. Ruan Yifeng: getting started with ECMAScript 6 – promise object
  2. In depth promise (1) — a detailed explanation of promise implementation
  3. The realization of promise class according to promise / A + specification

If you find this article useful, please add a star to GitHub. Thank you very much

In addition, there are other front-end tutorials and components on GitHub,
Interested children’s shoes can see, your support is my biggest motivation.

Recommended Today

ASP.NET Example of core MVC getting the parameters of the request

preface An HTTP request is a standard IO operation. The request is I, which is the input; the responsive o is the output. Any web development framework is actually doing these two things Accept the request and parse to get the parameters Render according to the parameters and output the response content So let’s learn […]