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

Two ways to configure Vue global methods

Table of contents 1. Introduction 2. The first me...

Detailed explanation of upgrading Python and installing pip under Linux

Linux version upgrade: 1. First, confirm that the...

How to build Git service based on http protocol on VMware+centOS 8

Table of contents 1. Cause 2. Equipment Informati...

Examples of new selectors in CSS3

Structural (position) pseudo-class selector (CSS3...

HTML implementation of a simple calculator with detailed ideas

Copy code The code is as follows: <!DOCTYPE ht...

Notes on upgrading to mysql-connector-java8.0.27

Recently, an online security scan found a vulnera...

CSS3 changes the browser scroll bar style

Note: This method is only applicable to webkit-ba...

Detailed explanation of the use cases of Vue listeners

The first one is to use jQuery's ajax to send...

MySQL 8.0.12 winx64 detailed installation tutorial

This article shares the installation tutorial of ...

A brief discussion on how to learn JS step by step

Table of contents Overview 1. Clearly understand ...

Methods and steps for deploying multiple war packages in Tomcat

1 Background JDK1.8-u181 and Tomcat8.5.53 were in...

Why MySQL chooses Repeatable Read as the default isolation level

Table of contents Oracle Isolation Levels MySQL I...

Detailed explanation of the order of JS object traversal

Some of you may have heard that the order of trav...

Nodejs error handling process record

This article takes the connection error ECONNREFU...