Home > Web Front-end > JS Tutorial > body text

Step-by-step tutorial on implementing Promise

coldplay.xixi
Release: 2020-09-02 17:23:14
forward
1639 people have browsed it

Step-by-step tutorial on implementing Promise

【Related learning recommendations: javascript video tutorial

Preface

Many JavaScript beginners have felt the fear of being dominated by callback hell, and they are not relieved until they master the Promise syntax. Although many languages ​​​​have already built-in Promise, the real promotion of it in JavaScript is jQuery 1.5's reconstruction of $.ajax, which supports Promise, and its usage is consistent with the chain call advocated by jQuery. And together. Later, when ES6 was born, everyone began to enter the era of universal Promise. Later, ES8 introduced async syntax to make JavaScript's asynchronous writing more elegant.

Today we will implement a Promise step by step. If you have not used Promise yet, it is recommended to familiarize yourself with Promise syntax before reading this article.

Constructor

In existing Promise/A The specification does not stipulate where the promise object comes from. In jQuery, the promise object is obtained by calling $.Deferred(). In ES6, the promise is obtained by instantiating the Promise class. object. Here we use ES syntax to construct a class and return the promise object through instantiation. Since Promise already exists, we temporarily name this class Deferred.

class Deferred {  constructor(callback) {    const resolve = () => {      // TODO
    }    const reject = () => {      // TODO
    }    try {
      callback(resolve, reject)
    } catch (error) {
      reject(error)
    }
  }
}复制代码
Copy after login

The constructor accepts a callback. When calling callback, you need to pass in two methods: resolve and reject.

State of Promise

Promise is divided into three states:

Step-by-step tutorial on implementing Promise
    ##⏳
  • Step-by-step tutorial on implementing Promise: Waiting, this is the initial state of Promise;
    Step-by-step tutorial on implementing Promise

The above is the detailed content of Step-by-step tutorial on implementing Promise. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template