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

Vue implements irregular screenshots

Table of contents Image capture through svg CSS p...

Teach you how to build Tencent Cloud Server (graphic tutorial)

This article was originally written by blogger We...

Web standards learning to understand the separation of structure and presentation

When discussing Web standards, one thing that alwa...

Detailed explanation of MySQL and Spring's autocommit

1 MySQL autocommit settings MySQL automatically c...

Solution for importing more data from MySQL into Hive

Original derivative command: bin/sqoop import -co...

40 fonts recommended for famous website logos

Do you know what fonts are used in the logo desig...

Steps to deploy ingress-nginx on k8s

Table of contents Preface 1. Deployment and Confi...

js to realize the function of uploading pictures

The principle of uploading pictures on the front ...

Solution to the long delay of MySQL database master-slave replication

Preface The delay of MySQL master-slave replicati...

Three strategies for rewriting MySQL query statements

Table of contents Complex query and step-by-step ...

Uncommon but useful tags in Xhtml

Xhtml has many tags that are not commonly used but...

Detailed explanation of MySQL three-value logic and NULL

Table of contents What is NULL Two kinds of NULL ...

mysql5.7.19 zip detailed installation process and configuration

MySQL v5.7.19 official version (32/64 bit install...

MySql grouping and randomly getting one piece of data from each group

Idea: Just sort randomly first and then group. 1....