Teach you to implement a simple promise step by step

Teach you to implement a simple promise step by step

Step 1: Build the framework

1. First we need to place a promise function body here and then add resolve and reject execution functions to it.

  function Promise(execotor) {}

2. The original promise has two main methods: then and catch, so we need to attach then and catch to the prototype of promise

  Promise.prototype.then = function (onResolved, onRejected) {}
  Promise.prototype.catch = function (onRejected) {}

3. Add several common methods to promise: resolve, reject, all, race, etc.

resolve: returns a promise object with a specified result

  Promise.resolve = function (value) { }

reject: method that returns a failed status

  Promise.reject = function (value) { }

all: Returns a promise object. This state is considered successful only when all promises are returned.

  Promise.all = function (value) { }

race: returns a promise object, whose state is determined by the first returned object. Whichever function in the race is executed first will return the first value directly, and the others will continue to execute.

  Promise.race = function (value) { }

4. Global declaration of mypromise

  window.Promise = Promise

5. Create a self-executing function to wrap all the above contents

(function (window) {

})()

Step 2 Fill in the built Promise framework

1. Fill function Promise()

(1) let self = this fixes the this inside a function. This this will play a big role later.

(2) self.status = 'pending' adds a basic status 'pending' to the Promise function body

(3) self.data = undefined creates a data source to store the results returned by resolve

(4) self.callbacks = [] creates an array to save all the callbacks in the promise

2. Fill in function resolve()

(1) if (self.status !== 'pending') { return } Check whether the status of the current incoming process is pending. If it is, continue with the following operation. If not, return directly.

There are three states in promise: pending, resolved, and rejected. These three states are switch variables. If the state changes from pending to other states, it cannot be changed.

(2) self.status = 'resolved' changes the status of the process to resolved

(3) self.data = value saves the value, which will be used in the callback in then.

(4) Put the most important execution function part. If there is a callback function to be executed in sele.data, execute it asynchronously immediately.

    if (self.callbacks.length > 0) {
      setTimeout(() => {
        self.callbacks.forEach(callbackObj => {
          callbackObj.onResolved(value)
        })
      }, 0)
    }

3. Fill function reject()

(1) Same as resolve function, abbreviated here

4. Fill in the execotor method

If an error occurs during the execution of the promise body, the error message is captured by the catch function, which will then jump to the function to execute a reject statement separately.

     try {
       execotor(resolve, reject)
     } catch (error) {
       reject(error)
     }

5. Fill in the .then function

First we need to distinguish the state of the incoming process. If it is pending, save the callback function. If it is not pending, do what it should do.

(1) if (self.status === 'pending') if the current status is pending, we save it

    self.callbacks.push({
      onResolved() { onResolved(self.data) },
      onRejected() { onRejected(self.data) }
    })

(2) else if (self.status === 'resolved') if status is resolved

Let's happily execute it.

    setTimeout(() => {
      onResolved(self.data)
    }, 0)

However, there is a state where resolve is not executed, but the state has changed. We cannot execute resolve but instead execute rejected.

   else{
     setTimeout(() => {
       onRejecyed(self.data)
     }, 0)
   }

After two steps as "simple" as how to put an elephant into a refrigerator, we have implemented a simple Promise

It’s simple, isn’t it? Call your friends to try it together!

Summarize

This is the end of this article about implementing a simple promise. For more information about implementing a simple promise, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed examples of using Promise in JavaScript
  • A brief talk about js promise is enough to read this article
  • Detailed explanation of Javascript Promise usage
  • Detailed explanation of Promise usage in JavaScript
  • JavaScript Promise Usage
  • Understanding the use of Promises in JavaScript

<<:  Usage and description of HTML tag tbody

>>:  How to solve the element movement caused by hover-generated border

Recommend

Real-time refresh of long connection on Vue+WebSocket page

Recently, the Vue project needs to refresh the da...

Detailed tutorial on building Gitlab server on CentOS8.1

There is no need to say much about the difference...

js implements a simple countdown

This article example shares the specific code of ...

Detailed explanation of the use of MySQL concatenation function CONCAT

The previous articles introduced the replacement ...

js precise calculation

var numA = 0.1; var numB = 0.2; alert( numA + num...

Detailed explanation of VUE Token's invalidation process

Table of contents Target Thought Analysis Code la...

Implementing a simple carousel based on JavaScript

This article shares the specific code of JavaScri...

A complete guide to CSS style attributes css() and width() in jQuery

Table of contents 1. Basic use of css(): 1.1 Get ...

Detailed explanation of the 14 common HTTP status codes returned by the server

HTTP Status Codes The status code is composed of ...

How to configure Http, Https, WS, and WSS in Nginx

Written in front In today's Internet field, N...

How to use and limit props in react

The props of the component (props is an object) F...

CSS uses calc() to obtain the current visible screen height

First, let's take a look at the relative leng...

How to access MySql through IP address

1. Log in to mysql: mysql -u root -h 127.0.0.1 -p...

Vue implements tree table

This article example shares the specific code of ...