Home>Article>Web Front-end> Step-by-step tutorial on implementing Promise

Step-by-step tutorial on implementing Promise

coldplay.xixi
coldplay.xixi forward
2020-09-02 17:22:46 1565browse

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 existingPromise/AThe 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 classDeferred.

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

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!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete