What is a promise
Promise is a class that is now a common asynchronous solution to the callback hell of asynchronous programming
Several common asynchronous programming methods
- Back off function
- Event listeners
- Release subscription
- promise
- Generator (not usually used)
- Async, await (ES8 syntax)
Promise versus the callback function
Promise versionlet api = new Promise((resolve,reject)=>{
resolve("Success");
reject("Failure")}) api.then (val=>{resolve(val)}).then(val=>{resolve(val)}).then(val=>{console.log(val) // success}) use the callback function $.get(url, data1 => { console.log(data1) $.get(data1.url, data2 => { console.log(data1) }) })Copy the code
Does that make it a little bit clearer
The use of the promise
- Promise is a constructor. New Promise returns a Promise object that takes an excutor execution function as an argument. Excutor takes two function type parameters resolve reject
// The excutor function executes immediately, taking resolve and reject as arguments // one for each Promise instancethenmethodslet promise = new Promise(function(resolve,reject){//excutor
resolve("Success");
reject("Failure"// this will be a big pity, onrejectd fail promise. Then (function(val){// ondepressing console.log(val) // succeed},function(err){//onrejectd console.log(err) // failed})Copy the code
Promise has three states
- Pendding Indicates the wait status, Resolved succeeds, and Rejected fails
1. In the Pendding waiting state -> Resolved successful state. 2
This is a big pity/pity. This state cannot be changed pending => depressing/Rejected
The Promise object method **
Handwritten Promise code
functionPromise(executor){// Promise has three state pending depressing this. Status ='pending'; This. value = undefined; // This. Reason = undefined; // Information returned in failed stateletself = this; self.onResolveCallbacks = []; Ondepressing function self.onRejectedCallbacks = []; // Stores the onRejected function corresponding to the failed statefunctionReoslve (value){// Becomes successfulif(self.status === 'pending'){
self.value = value;
self.status = 'fulfilled';
self.onResolveCallbacks.forEach(fn=>fn())
}
}
functionReject (reason){// Becomes a reject stateif(self.status === 'pending'){
self.reason = reason;
self.status = 'rejected'; self.onRejectedCallbacks.forEach(fn=>fn()) } } try{ executor(reoslve,reject); }catch(e){ reject(e); }} // This method should be compatible with other people's promisesfunction resolvePromise(promise2,x,resolve,reject){
if(promise2 === x){// Prevent returning promises andthenThe method returns the same promisereturn reject(new TypeError('Circular reference'));
}
if(x! == null && (typeof x ==='object' || typeof x === 'function')) {/ / {}let called;
try{
let then= x.then; // See if this object is availablethenMethod, if x is a promise {then: undefined}if(typeof then= = ='function'){
then.call(x,y=>{
if(called) return
called = true; / / if the return is a promise the promise, resolve is likely to be a promise, the result of the recursive analysis until the y is a constant resolvePromise (promise2, y, resolve, reject)}, r = > {if(called) return// Prevent a failed call and a successful call called =true;
reject(r);
});
}else{ resolve(x); / / {then: {}} {thenCatch (e){// thisthenMethods are defined via ObjectDefinePropertyif(called) return
called = true; Reject (e); reject(e); }}else{ resolve(x); }} promise.prototype. then =function(onfulfilled, onfulfilled){// Parameter optional onfulfilled = typeof onfulfilled === ='function'? onfulfilled :val=>val; onrejected = typeof onrejected =='function'? onrejected :err=>{throw err}letself = this; // Each promise must return a new state guarantee that can be chain-calledlet promise2 = new Promise(function(resolve,reject){
if(self.status === 'fulfilled') {setTimeout(()=>{
try{
letx = onfulfilled(self.value); resolvePromise(promise2,x,resolve,reject) }catch(e){ reject(e); }})}if(self.status === 'rejected') {setTimeout(()=>{
try{
letx = onrejected(self.reason); resolvePromise(promise2,x,resolve,reject) }catch(e){ reject(e); }})}if(self.status === 'pending'){
self.onResolveCallbacks.push(function() {setTimeout(()=>{
try{
letx = onfulfilled(self.value); resolvePromise(promise2,x,resolve,reject) }catch(e){ reject(e); }})}); self.onRejectedCallbacks.push(function() {setTimeout(()=>{
try{
letx = onrejected(self.reason); resolvePromise(promise2,x,resolve,reject) }catch(e){ reject(e); }})})}});return promise2
}
// npm install promises-aplus-tests -g
// promises-aplus-tests promise.js
Promise.deferred = function() {let dfd = {};
dfd.promise = new Promise((resolve,reject)=>{
dfd.resolve = resolve;
dfd.reject = reject;
});
return dfd;
};
module.exports = Promise
Copy the code