Promise to learn
Promise is a way around THE callback hell in JS. It’s an object that passes messages for asynchronous operations, whose results are known after a while (what asynchronous means), and goes through three states: Pending, resolve, reject. When pending, it can only move to resolve or reject after a certain amount of time, and the result cannot be reversed: The result cannot move from resolve to reject, and reject cannot move from resolve. The Promise object is already built into ES6, and the benefits of using it are:
- Can avoid callback hell, can chain call;
- Code clarity;
Make a simple Promise yourself
We’ll define a Promise constructor that contains five variables: the successful callback, the failed callback, the state, and the successful and failed callback then. Two callback methods: resolve and reject; And adding then methods to the prototype chain;
Code implementation (if named: myPromise.js) :
function Promise(executor) {
let self = this;
self.value = undefined;
self.reason = undefined;
self.status = 'pending';
self.onResolvedCallbacks = [];
self.onRejectedCallbacks = [];
function resolve(value) {
if (self.status === 'pending'Self. value = value; self. reject = value; self.status ='resolved'; self.onResolvedCallbacks.forEach(fn => fn()); }}function reject(reason) {
if (self.status === 'pending') {
self.reason = reason;
self.status = 'rejected';
self.onRejectedCallbacks.forEach(fn => fn());
}
}
try {
executor(resolve, reject);
}catch(e) {
reject(e);
}
}
Promise.prototype.then = function(onFulfilled, onRejected) {
let self = this;
if (self.status === 'resolved') {
onFulfilled(self.value);
}
if (self.status === 'rejected') {
onRejected(self.reason);
}
if (self.status === 'pending') {
self.onResolvedCallbacks.push(() => {
onFulfilled(self.value);
});
self.onRejectCallbacks.push(() => {
onRejected(self.reason);
});
}
}
module.exports = Promise
Copy the code
Code use:
let Promise = require('./myPromise');
letpromise = new Promise((resolve, reject) => { reject(); }); promise.then((data) => { console.log('success:' + data);
}, (err) => {
console.log('error:' + err);
})
Copy the code
End of the stroke
The above is A simple function to realize the promise, we can according to the promise A+ specification to complete the full implementation of the promise.