Home > Article > Web Front-end > Step-by-step tutorial on implementing Promise
【Related learning recommendations: javascript video tutorial】
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.
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) } } }复制代码
The constructor accepts a callback. When calling callback, you need to pass in two methods: resolve and reject.
Promise is divided into three states:
: Waiting, this is the initial state of 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!