Promise principle handwritten implementation of promise and async await

1. Understanding of Promise

MDNIt is explained like this:

An Promiseobject represents a promise proxy whose value is not necessarily known when it is created. It allows you to associate the final success return value or failure reason of an asynchronous operation with the corresponding handler. This allows asynchronous methods to return values ​​just like synchronous methods: asynchronous methods do not return the final value immediately, but instead return one promiseso that the value can be handed over to the user at some point in the future.

A Promisemust be in one of the following states:

Pending ( pending): Initial status, neither honored nor rejected.
Cashed ( fulfilled): Means the operation was completed successfully.
Rejected ( rejected): means the operation failed.

It’s a bit hard to pronounce, but in layman’s terms it’s:

So-called Promise, simply put, it is a container that stores the results of an event (usually an asynchronous operation) that will end in the future.

PromiseIs a constructor, it has several methods, all, reject, and other methods on its prototype; the object is used to encapsulate an asynchronous operation and can obtain itsresolvethen、catchpromisesuccess failureThe result value of

2. Composition of Promise

let p = new Promise([executor])
  • new Promise() Inside the brackets must be an executable function
    • new Promise, the function Promisewill be executed immediately internally[executor]
    • Functions are generally used to manage an asynchronous programming code. It is also possible not to control asynchronous programming.
    • [exector]Pass two values ​​to the function at the same time :resolve、rejecct

3. Basic use of Promise

3.1 new Promise() is an instance

let p1 = new Promise((resolve, reject) => {
    
    });
console.log(p1);

Print p1 results
Print p1 results

The attributes in square brackets [[]]are called built-in attributes: attributes inside the browser and cannot be operated.

  • pis Promisean instance of class
    • Built-in private properties
      • [[PromiseState]] :Instance status:pending、fulfilled/resolved、rejected
      • [[PromiseResult]]:instance value
    • Public property method Promise.prototype
      • then
      • catch
      • finally
      • Symbol(Symbol.toStringTag), you can use Object.prototype.toString.call(p1)to detect whether it is promise, the result is"[object Promise]"

Note: Promise is asynchronous, new Promise is synchronous, and the internal function will be executed immediately

3.1 Promise modification status

The purpose of [executor]execution resolve/rejectis to change promisethe state and value (result) of the instance.

Once the promise state is changed, it cannot be changed to other states.

let p1 = new Promise((resolve, reject) => {
    
    
	resolve("ok");
	reject("no");
});
console.log(p1);

resolveIf rejectboth and are executed, only the first status (success)/value will be returned. If commented out resolve, the failure status/value will be returned, as shown below.
Insert image description here
If [executor]the function reports an error, Promisethe status will become rejected, and the result is the reason for the error. PromiseAn internal process is done information capturetry catch

let p1 = new Promise((resolve, reject) => {
    
    
	// reject("no");
	// resolve("ok");
	console.log(a);
});
console.log(p1);

Insert image description here

4. Why use Promise?

1. The way to specify the callback function is more flexible

No promise: must be specified before starting the asynchronous task

Use promise:: Start an asynchronous task => Return a promie object => Bind a callback function to the promise object
(you can even specify/multiple after the asynchronous task ends

2. Support chain calls, which can solve the callback hell problem

  1. What is callback hell?
    Callback functions are called nested. The result of the asynchronous execution of the external callback function is the condition for the execution of the nested callback.
  2. Disadvantages of callback hell?
    It is not easy to read and handle exceptions
  3. Solution?
    promiseChain calls
  4. ultimate solution
    async/await

5. Promise API

1. Promise constructor:Promise (excutor) {}

  • executorFunction: Executor(resolve, reject) => {}
  • resolveFunction: The function we call when the internal definition is successful value => {}
  • rejectFunction: The function we call when the internal definition failsreason => {}

Description: executorIt will be Promisecalled synchronously internally immediately, and the asynchronous operation will be executed in the executor.

2. Promise.prototype.then method:p.then(onResolved, onRejected)

  • onResolved Function: success callback function (value) => {}
  • onRejectedFunction: callback function on failure(reason) => {}

Description: Specify valuethe success callback used to get success and reason the failure callback used to get failure, and return a new promise object

3. Promise.prototype.catch method:p.catch(onRejected)

  • onRejectedFunction: callback function on failure(reason) => {}

Note: This is syntactic sugar for then(), equivalent to: then(undefined/null, onRejected)

4. Promise.resolve method:Promise.resolve(value)

value: Promise The parameter to be parsed by the object, which can also be a success or failure Promiseobject

Description: Returns a success/failure promise object

  • If the parameter passed in is an object of non-Promise type, the returned result is a successful promise object.

    let p1 = Promise.resolve(555);
    console.log(p1); // Promise {<fulfilled>: 555}
    

    Insert image description here

  • If the parameter passed in is a Promise object, the result of the parameter determines the result of resolve

    let p2 = Promise.resolve(new Promise((resolve, reject) => {
          
          
        // resolve('OK'); // 成功的Promise
        reject('Error');
    }));
    console.log(p2);
    p2.catch(reason => {
          
          
        console.log(reason);
    })
    
    

    Insert image description here

5. Promise.reject method:Promise.reject (reason)

reason: Reason for failure
Description: Returns a failed promise object

let p = Promise.reject(555);
let p2 = Promise.reject('hhh');
let p3 = Promise.reject(new Promise((resolve, reject) => {
    
    
    resolve('OK');
}));

console.log(p);
console.log(p2);
console.log(p3);

Insert image description here
The Promise.resolve()/Promise.reject() method is a syntax sugar used to quickly get the Promise object

//产生一个成功值为1的promise对象
new Promise((resolve, reject) => {
    
    
 resolve(1)
})
//相当于
const p1 = Promise.resolve(1)
const p2 = Promise.resolve(2)
const p3 = Promise.reject(3)

p1.then(value => {
    
    console.log(value)}) // 1
p2.then(value => {
    
    console.log(value)}) // 2
p3.catch(reason => {
    
    console.log(reason)}) // 3

6. Promise.all method:Promise.all(iterable)

iterable: an iterable object containing n promises, such as Array or String

Description: Return a new promise. It will succeed only if all promises succeed. If one fails, it will fail directly.

To get each result returned by promise, you need to use then

 let p1 = new Promise((resolve, reject) => {
    
    
     resolve('OK');
 })
 // let p2 = Promise.resolve('Success');
 let p2 = Promise.reject('Error');
 let p3 = Promise.resolve('Oh Yeah');
 
 //
 const result = Promise.all([p1, p2, p3]);

 console.log(result);
 
 result.then(data => {
    
    
        console.log(data);
      });

Insert image description here

7. Promise.race method:Promise.race(iterable)

iterable: an iterable object containing n promises, such as Array or String

Description: Return a new promise. The result status of the first completed promise is the final result status. Whoever
completes it first will be output (regardless of success or failure).

 let p1 = new Promise((resolve, reject) => {
    
    
     setTimeout(() => {
    
    
         resolve('OK');
     }, 1000);
 })
 let p2 = Promise.resolve('Success');
 let p3 = Promise.resolve('Oh Yeah');

 //调用
 const result = Promise.race([p1, p2, p3]);

 console.log(result);

Insert image description here

6. Several key issues with promises

6.1 How to change the state of promise?

  • resolve(value): If it is currently pending, it will become resolved.
  • reject(reason): If it is currently pending, it will become rejected.
  • Throws an exception: If it is currently pending, it will become rejected.
let p = new Promise((resolve, reject) => {
    
    
    //1. resolve 函数
    // resolve('ok'); // pending   => fulfilled (resolved)
    //2. reject 函数
    // reject("error");// pending  =>  rejected 
    //3. 抛出错误
    // throw '出问题了';
});

console.log(p);

6.2 If a promise specifies multiple success/failure callback functions, will they all be called?

Will be called when the promise changes to the corresponding state

let p = new Promise((resolve, reject) => {
    
    
    resolve('OK'); 
});

///指定回调 - 1
p.then(value => {
    
    
    console.log(value);
});

//指定回调 - 2
p.then(value => {
    
    
    alert(value);
});

6.3 Who should change the promise state or specify the callback function first?

It's possible. Generally, you specify the callback first and then change the state. But you can also change the state first and then specify the callback.

Change the status first and then specify the callback:

  • Called directly in the executor resolve()/reject()
  • When a callback is specified, the callback function will be called and the data will be obtained.

Specify the callback first and then change the status:

  • asynchronous call resolve()/reject()
  • When the state changes, the callback function will be called to get the data. In short, getting the data is in the last step.
 let p = new Promise((resolve, reject) => {
    
    
     setTimeout(() => {
    
    
         resolve('OK');
     }, 1000);
 });

 p.then(value => {
    
    
     console.log(value);
 },reason=>{
    
    
     
 })

6.4 What determines the result status of the new promise returned by promise.then()?

  • If an exception is thrown, the new promise becomes rejected, and reason is the thrown exception.
  • If any value other than promise is returned, the new promise becomes resolved and value is the returned value.
  • If another new promise is returned, the result of this promise will become the result of the new promise
let p = new Promise((resolve, reject) => {
    
    
    resolve('ok');
});
//执行 then 方法
let result = p.then(value => {
    
    
    // console.log(value);
    //1. 抛出错误
    // throw '出了问题';
    //2. 返回结果是非 Promise 类型的对象
    // return 555;
    //3. 返回结果是 Promise 对象
    // return new Promise((resolve, reject) => {
    
    
    //     // resolve('success');
    //     reject('error');
    // });
}, reason => {
    
    
    console.warn(reason);
});

console.log(result);

Insert image description here

6.5 How does promise concatenate multiple operation tasks?

  • Promise's then() returns a new promise, which can start chain calls of then()
  • Concatenate multiple synchronous/asynchronous tasks through chain calls of then
let p = new Promise((resolve, reject) => {
    
    
  setTimeout(() => {
    
    
      resolve('OK');
  }, 1000);
});

p.then(value => {
    
    
  return new Promise((resolve, reject) => {
    
    
      resolve("success");
  });
}).then(value => {
    
    
  console.log(value); // success
}).then(value => {
    
    
  console.log(value); // undefined   上一个then没有返回
})

6.6 Exception penetration of promise

  • When using promise's then chain call, you can specify a failure callback at the end.
  • If an exception occurs in any previous operation, it will be passed to the final failed callback for processing.
let p = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        resolve('OK');
        // reject('Err');
    }, 1000);
});

p.then(value => {
    
    
    // console.log(111);
    throw '失败啦!';
}).then(value => {
    
    
    console.log(222);
}).then(value => {
    
    
    console.log(333);
}).catch(reason => {
    
    
    console.warn(reason);
});

6.7 Breaking the promise chain?

When using promise's then chain call, it will be interrupted in the middle and the subsequent callback function will no longer be called.

Solution: Return a promise object in pending state in the callback function

let p = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        resolve('OK');
    }, 1000);
});

p.then(value => {
    
    
    console.log(111);
    //有且只有一个方式
    return new Promise(() => {
    
    });
}).then(value => {
    
    
    console.log(222);
}).then(value => {
    
    
    console.log(333);
}).catch(reason => {
    
    
    console.warn(reason);
});

7. Handwritten promises

<script src="./promise.js"></script>

let p = new Promise((resolve, reject) => {
    
    
    resolve('OK');
});

p.then(value => {
    
    
    console.log(value);
}, reason=>{
    
    
    console.warn(reason);
})

7.1 Define the overall structure

function Promise(executor){
    
    

}
//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
    
    
}

7.2 Resolve and reject structure construction

//声明构造函数
function Promise(executor){
    
    
    //resolve 函数
    function resolve(data){
    
    

    }
    //reject 函数
    function reject(data){
    
    

    }

    //同步调用『执行器函数』
    executor(resolve, reject); //需要定义resolve和reject
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
    
    

}

7.3 Code implementation of resolve and reject

We know that resolve and reject do two things: change the state and set the result value.

//声明构造函数
function Promise(executor){
    
    
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
    
    
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
    }
    //reject 函数
    function reject(data){
    
    
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
    }

    //同步调用『执行器函数』
    executor(resolve, reject);
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
    
    

}

7.4 throw throws an exception and changes the state

There are three ways to change the state: resolve, reject, throw

Reject is called at the executor function, so try catch needs to be added to the executor.

//声明构造函数
function Promise(executor){
    
    
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
    
    
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
    }
    //reject 函数
    function reject(data){
    
    
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
    }
    try{
    
    
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
    
    
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
    
    

}

7.5 The status can only be modified once

Judgment status if(self.PromiseState !== 'pending') return;

//声明构造函数
function Promise(executor){
    
    
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
    }
    //reject 函数
    function reject(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
    }
    try{
    
    
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
    
    
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
    
    

}

7.6 then method execution callback

    //调用回调函数  PromiseState
    if(this.PromiseState === 'fulfilled'){
    
    
        onResolved(this.PromiseResult);
    }
    if(this.PromiseState === 'rejected'){
    
    
        onRejected(this.PromiseResult);
    }
//声明构造函数
function Promise(executor){
    
    
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
    }
    //reject 函数
    function reject(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
    }
    try{
    
    
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
    
    
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
    
    
    //调用回调函数  PromiseState
    if(this.PromiseState === 'fulfilled'){
    
    
        onResolved(this.PromiseResult);
    }
    if(this.PromiseState === 'rejected'){
    
    
        onRejected(this.PromiseResult);
    }
}

7.7 Execution of asynchronous task callbacks

//实例化对象
let p = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        // resolve('OK');
        reject("error");
    }, 1000);
});

p.then(value => {
    
    
    console.log(value);
}, reason=>{
    
    
    console.warn(reason);
});

console.log(p);

Asynchronous calls have to wait until the state changes to execute the callback, so execute the callback in the resolve/reject function and add the callback function in the then method.

//声明构造函数
function Promise(executor){
    
    
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //声明属性
    this.callback = {
    
    };
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //调用成功的回调函数
        if(self.callback.onResolved){
    
    
            self.callback.onResolved(data);
        }
    }
    //reject 函数
    function reject(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //执行回调
        if(self.callback.onResolved){
    
    
            self.callback.onResolved(data);
        }
    }
    try{
    
    
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
    
    
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
    
    
    //调用回调函数  PromiseState
    if(this.PromiseState === 'fulfilled'){
    
    
        onResolved(this.PromiseResult);
    }
    if(this.PromiseState === 'rejected'){
    
    
        onRejected(this.PromiseResult);
    }
    //判断 pending 状态
    if(this.PromiseState === 'pending'){
    
    
        //保存回调函数
        this.callback = {
    
    
            onResolved: onResolved,
            onRejected: onRejected
        }
    }
}

7.8 Specify the implementation of multiple callbacks

//实例化对象
let p = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        // resolve('OK');
        reject('No');
    }, 1000);
});

p.then(value => {
    
    
    console.log(value);
}, reason=>{
    
    
    console.warn(reason);
});

p.then(value => {
    
    
    alert(value);
}, reason=>{
    
    
    alert(reason);
});

console.log(p);

If there is only one then, the callback function can be stored as an object, but in order to implement the chain call of then, the promise needs to use an array to store the callback function, so that the callback function in each then will be executed.

//声明构造函数
function Promise(executor){
    
    
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //声明属性
    this.callbacks = [];
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //调用成功的回调函数
        self.callbacks.forEach(item => {
    
    
            item.onResolved(data);
        });
    }
    //reject 函数
    function reject(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //执行失败的回调
        self.callbacks.forEach(item => {
    
    
            item.onRejected(data);
        });
    }
    try{
    
    
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
    
    
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
    
    
    //调用回调函数  PromiseState
    if(this.PromiseState === 'fulfilled'){
    
    
        onResolved(this.PromiseResult);
    }
    if(this.PromiseState === 'rejected'){
    
    
        onRejected(this.PromiseResult);
    }
    //判断 pending 状态
    if(this.PromiseState === 'pending'){
    
    
        //保存回调函数
        this.callbacks.push({
    
    
            onResolved: onResolved,
            onRejected: onRejected
        });
    }
}

7.9 Modify the status synchronously and the then method returns the result

The return result of the then method is a promise object

//声明构造函数
function Promise(executor){
    
    
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //声明属性
    this.callbacks = [];
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //调用成功的回调函数
        self.callbacks.forEach(item => {
    
    
            item.onResolved(data);
        });
    }
    //reject 函数
    function reject(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //执行失败的回调
        self.callbacks.forEach(item => {
    
    
            item.onRejected(data);
        });
    }
    try{
    
    
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
    
    
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
    
    
    return new Promise((resolve, reject) => {
    
    
        //调用回调函数  PromiseState
        if(this.PromiseState === 'fulfilled'){
    
    
            try{
    
    
                //获取回调函数的执行结果
                let result = onResolved(this.PromiseResult);
                //判断
                if(result instanceof Promise){
    
    
                    //如果是 Promise 类型的对象
                    result.then(v => {
    
    
                        resolve(v);
                    }, r=>{
    
    
                        reject(r);
                    })
                }else{
    
    
                    //结果的对象状态为『成功』
                    resolve(result);
                }
            }catch(e){
    
    
                reject(e);
            }
        }
        if(this.PromiseState === 'rejected'){
    
    
            onRejected(this.PromiseResult);
        }
        //判断 pending 状态
        if(this.PromiseState === 'pending'){
    
    
            //保存回调函数
            this.callbacks.push({
    
    
                onResolved: onResolved,
                onRejected: onRejected
            });
        }
    })
}

7.10 Asynchronously modify status then method returns result

//声明构造函数
function Promise(executor){
    
    
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //声明属性
    this.callbacks = [];
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //调用成功的回调函数
        self.callbacks.forEach(item => {
    
    
            item.onResolved(data);
        });
    }
    //reject 函数
    function reject(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //执行失败的回调
        self.callbacks.forEach(item => {
    
    
            item.onRejected(data);
        });
    }
    try{
    
    
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
    
    
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
    
    
    const self = this;
    return new Promise((resolve, reject) => {
    
    
        //调用回调函数  PromiseState
        if(this.PromiseState === 'fulfilled'){
    
    
            try{
    
    
                //获取回调函数的执行结果
                let result = onResolved(this.PromiseResult);
                //判断
                if(result instanceof Promise){
    
    
                    //如果是 Promise 类型的对象
                    result.then(v => {
    
    
                        resolve(v);
                    }, r=>{
    
    
                        reject(r);
                    })
                }else{
    
    
                    //结果的对象状态为『成功』
                    resolve(result);
                }
            }catch(e){
    
    
                reject(e);
            }
        }
        if(this.PromiseState === 'rejected'){
    
    
            onRejected(this.PromiseResult);
        }
        //判断 pending 状态
        if(this.PromiseState === 'pending'){
    
    
            //保存回调函数
            this.callbacks.push({
    
    
                onResolved: function(){
    
    
                    try{
    
    
                        //执行成功回调函数
                        let result = onResolved(self.PromiseResult);
                        //判断
                        if(result instanceof Promise){
    
    
                            result.then(v => {
    
    
                                resolve(v);
                            }, r=>{
    
    
                                reject(r);
                            })
                        }else{
    
    
                            resolve(result);
                        }
                    }catch(e){
    
    
                        reject(e);
                    }
                },
                onRejected: function(){
    
    
                    try{
    
    
                        //执行成功回调函数
                        let result = onRejected(self.PromiseResult);
                        //判断
                        if(result instanceof Promise){
    
    
                            result.then(v => {
    
    
                                resolve(v);
                            }, r=>{
    
    
                                reject(r);
                            })
                        }else{
    
    
                            resolve(result);
                        }
                    }catch(e){
    
    
                        reject(e);
                    }
                }
            });
        }
    })
}

7.11 The then method optimizes and encapsulates callback

//声明构造函数
function Promise(executor){
    
    
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //声明属性
    this.callbacks = [];
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //调用成功的回调函数
        self.callbacks.forEach(item => {
    
    
            item.onResolved(data);
        });
    }
    //reject 函数
    function reject(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //执行失败的回调
        self.callbacks.forEach(item => {
    
    
            item.onRejected(data);
        });
    }
    try{
    
    
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
    
    
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
    
    
    const self = this;
    return new Promise((resolve, reject) => {
    
    
        //封装函数
        function callback(type){
    
    
            try{
    
    
                //获取回调函数的执行结果
                let result = type(self.PromiseResult);
                //判断
                if(result instanceof Promise){
    
    
                    //如果是 Promise 类型的对象
                    result.then(v => {
    
    
                        resolve(v);
                    }, r=>{
    
    
                        reject(r);
                    })
                }else{
    
    
                    //结果的对象状态为『成功』
                    resolve(result);
                }
            }catch(e){
    
    
                reject(e);
            }
        }
        //调用回调函数  PromiseState
        if(this.PromiseState === 'fulfilled'){
    
    
            callback(onResolved);
        }
        if(this.PromiseState === 'rejected'){
    
    
            callback(onRejected);
        }
        //判断 pending 状态
        if(this.PromiseState === 'pending'){
    
    
            //保存回调函数
            this.callbacks.push({
    
    
                onResolved: function(){
    
    
                    callback(onResolved);
                },
                onRejected: function(){
    
    
                    callback(onRejected);
                }
            });
        }
    })
}

7.12 Catch method exception penetration and value transfer

//实例化对象
let p = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        // reject('OK');
        resolve('OK');
    }, 1000);
});

//值传递
p.then()
.then(value=>{
    
    
    console.log(222);
}).then(value => {
    
    
    console.log(333);
}).catch(reason => {
    
    
    console.warn(reason);
});

Add a catch method and need to determine whether the first and second parameters of the callback function exist

 //判断回调函数参数
    if(typeof onRejected !== 'function'){
    
    
        onRejected = reason => {
    
    
            throw reason;
        }
    }
    if(typeof onResolved !== 'function'){
    
    
        onResolved = value => value;
        //value => { return value};
    }
//声明构造函数
function Promise(executor){
    
    
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //声明属性
    this.callbacks = [];
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //调用成功的回调函数
        self.callbacks.forEach(item => {
    
    
            item.onResolved(data);
        });
    }
    //reject 函数
    function reject(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //执行失败的回调
        self.callbacks.forEach(item => {
    
    
            item.onRejected(data);
        });
    }
    try{
    
    
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
    
    
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
    
    
    const self = this;
    //判断回调函数参数
    if(typeof onRejected !== 'function'){
    
    
        onRejected = reason => {
    
    
            throw reason;
        }
    }
    if(typeof onResolved !== 'function'){
    
    
        onResolved = value => value;
        //value => { return value};
    }
    return new Promise((resolve, reject) => {
    
    
        //封装函数
        function callback(type){
    
    
            try{
    
    
                //获取回调函数的执行结果
                let result = type(self.PromiseResult);
                //判断
                if(result instanceof Promise){
    
    
                    //如果是 Promise 类型的对象
                    result.then(v => {
    
    
                        resolve(v);
                    }, r=>{
    
    
                        reject(r);
                    })
                }else{
    
    
                    //结果的对象状态为『成功』
                    resolve(result);
                }
            }catch(e){
    
    
                reject(e);
            }
        }
        //调用回调函数  PromiseState
        if(this.PromiseState === 'fulfilled'){
    
    
            callback(onResolved);
        }
        if(this.PromiseState === 'rejected'){
    
    
            callback(onRejected);
        }
        //判断 pending 状态
        if(this.PromiseState === 'pending'){
    
    
            //保存回调函数
            this.callbacks.push({
    
    
                onResolved: function(){
    
    
                    callback(onResolved);
                },
                onRejected: function(){
    
    
                    callback(onRejected);
                }
            });
        }
    })
}

//添加 catch 方法
Promise.prototype.catch = function(onRejected){
    
    
    return this.then(undefined, onRejected);
}

7.13 resolve method encapsulation

const p = Promise.resolve('OK');
const p2 = Promise.resolve(new Promise((resolve, reject) => {
    
    
    // resolve('Success');
    reject("error");
}));
const p3 = Promise.resolve(Promise.resolve('Oh Yeah'));

console.log(p3);

Add the resolve method. Note that resolve is a function of Promise, not a method of the instance object.

//添加 resolve 方法
Promise.resolve = function(value){
    
    
    //返回promise对象
    return new Promise((resolve, reject) => {
    
    
        if(value instanceof Promise){
    
    
            value.then(v=>{
    
    
                resolve(v);
            }, r=>{
    
    
                reject(r);
            })
        }else{
    
    
            //状态设置为成功
            resolve(value);
        }
    });
}
//声明构造函数
function Promise(executor){
    
    
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //声明属性
    this.callbacks = [];
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //调用成功的回调函数
        self.callbacks.forEach(item => {
    
    
            item.onResolved(data);
        });
    }
    //reject 函数
    function reject(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //执行失败的回调
        self.callbacks.forEach(item => {
    
    
            item.onRejected(data);
        });
    }
    try{
    
    
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
    
    
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

7.14 reject method encapsulation

//添加 reject 方法
Promise.reject = function(reason){
    
    
    return new Promise((resolve, reject)=>{
    
    
        reject(reason);
    });
}

7.15 all method encapsulation

//添加 all 方法
Promise.all = function(promises){
    
    
    //返回结果为promise对象
    return new Promise((resolve, reject) => {
    
    
        //声明变量
        let count = 0;
        let arr = [];
        //遍历
        for(let i=0;i<promises.length;i++){
    
    
            //
            promises[i].then(v => {
    
    
                //得知对象的状态是成功
                //每个promise对象 都成功
                count++;
                //将当前promise对象成功的结果 存入到数组中
                arr[i] = v;
                //判断
                if(count === promises.length){
    
    
                    //修改状态
                    resolve(arr);
                }
            }, r => {
    
    
                reject(r);
            });
        }
    });
}

7.16 race method encapsulation

//添加 race 方法
Promise.race = function(promises){
    
    
    return new Promise((resolve, reject) => {
    
    
        for(let i=0;i<promises.length;i++){
    
    
            promises[i].then(v => {
    
    
                //修改返回对象的状态为 『成功』
                resolve(v);
            },r=>{
    
    
                //修改返回对象的状态为 『失败』
                reject(r);
            })
        }
    });
}

7.15 Implementation of asynchronous execution of then method callback

let p1 = new Promise((resolve, reject) => {
    
    
    reject('OK');
    console.log(111);
});

p1.then(value => {
    
    
    console.log(222);
}, reason => {
    
    
    console.log(444);
});

console.log(333);

Print result: 111 333 444

If you want to implement it, you need to add the macro task setTimeOut

//声明构造函数
function Promise(executor){
    
    
    //添加属性
    this.PromiseState = 'pending';
    this.PromiseResult = null;
    //声明属性
    this.callbacks = [];
    //保存实例对象的 this 的值
    const self = this;// self _this that
    //resolve 函数
    function resolve(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'fulfilled';// resolved
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //调用成功的回调函数
        setTimeout(() => {
    
    
            self.callbacks.forEach(item => {
    
    
                item.onResolved(data);
            });
        });
    }
    //reject 函数
    function reject(data){
    
    
        //判断状态
        if(self.PromiseState !== 'pending') return;
        //1. 修改对象的状态 (promiseState)
        self.PromiseState = 'rejected';// 
        //2. 设置对象结果值 (promiseResult)
        self.PromiseResult = data;
        //执行失败的回调
        setTimeout(() => {
    
    
            self.callbacks.forEach(item => {
    
    
                item.onRejected(data);
            });
        });
    }
    try{
    
    
        //同步调用『执行器函数』
        executor(resolve, reject);
    }catch(e){
    
    
        //修改 promise 对象状态为『失败』
        reject(e);
    }
}

//添加 then 方法
Promise.prototype.then = function(onResolved, onRejected){
    
    
    const self = this;
    //判断回调函数参数
    if(typeof onRejected !== 'function'){
    
    
        onRejected = reason => {
    
    
            throw reason;
        }
    }
    if(typeof onResolved !== 'function'){
    
    
        onResolved = value => value;
        //value => { return value};
    }
    return new Promise((resolve, reject) => {
    
    
        //封装函数
        function callback(type){
    
    
            try{
    
    
                //获取回调函数的执行结果
                let result = type(self.PromiseResult);
                //判断
                if(result instanceof Promise){
    
    
                    //如果是 Promise 类型的对象
                    result.then(v => {
    
    
                        resolve(v);
                    }, r=>{
    
    
                        reject(r);
                    })
                }else{
    
    
                    //结果的对象状态为『成功』
                    resolve(result);
                }
            }catch(e){
    
    
                reject(e);
            }
        }
        //调用回调函数  PromiseState
        if(this.PromiseState === 'fulfilled'){
    
    
            setTimeout(() => {
    
    
                callback(onResolved);
            });
        }
        if(this.PromiseState === 'rejected'){
    
    
            setTimeout(() => {
    
    
                callback(onRejected);
            });
        }
        //判断 pending 状态
        if(this.PromiseState === 'pending'){
    
    
            //保存回调函数
            this.callbacks.push({
    
    
                onResolved: function(){
    
    
                    callback(onResolved);
                },
                onRejected: function(){
    
    
                    callback(onRejected);
                }
            });
        }
    })
}

//添加 catch 方法
Promise.prototype.catch = function(onRejected){
    
    
    return this.then(undefined, onRejected);
}

//添加 resolve 方法
Promise.resolve = function(value){
    
    
    //返回promise对象
    return new Promise((resolve, reject) => {
    
    
        if(value instanceof Promise){
    
    
            value.then(v=>{
    
    
                resolve(v);
            }, r=>{
    
    
                reject(r);
            })
        }else{
    
    
            //状态设置为成功
            resolve(value);
        }
    });
}

//添加 reject 方法
Promise.reject = function(reason){
    
    
    return new Promise((resolve, reject)=>{
    
    
        reject(reason);
    });
}

//添加 all 方法
Promise.all = function(promises){
    
    
    //返回结果为promise对象
    return new Promise((resolve, reject) => {
    
    
        //声明变量
        let count = 0;
        let arr = [];
        //遍历
        for(let i=0;i<promises.length;i++){
    
    
            //
            promises[i].then(v => {
    
    
                //得知对象的状态是成功
                //每个promise对象 都成功
                count++;
                //将当前promise对象成功的结果 存入到数组中
                arr[i] = v;
                //判断
                if(count === promises.length){
    
    
                    //修改状态
                    resolve(arr);
                }
            }, r => {
    
    
                reject(r);
            });
        }
    });
}

//添加 race 方法
Promise.race = function(promises){
    
    
    return new Promise((resolve, reject) => {
    
    
        for(let i=0;i<promises.length;i++){
    
    
            promises[i].then(v => {
    
    
                //修改返回对象的状态为 『成功』
                resolve(v);
            },r=>{
    
    
                //修改返回对象的状态为 『失败』
                reject(r);
            })
        }
    });
}

7.16 Implementation of class version



class Promise{
    
    
    //构造方法
    constructor(executor){
    
    
        //添加属性
        this.PromiseState = 'pending';
        this.PromiseResult = null;
        //声明属性
        this.callbacks = [];
        //保存实例对象的 this 的值
        const self = this;// self _this that
        //resolve 函数
        function resolve(data){
    
    
            //判断状态
            if(self.PromiseState !== 'pending') return;
            //1. 修改对象的状态 (promiseState)
            self.PromiseState = 'fulfilled';// resolved
            //2. 设置对象结果值 (promiseResult)
            self.PromiseResult = data;
            //调用成功的回调函数
            setTimeout(() => {
    
    
                self.callbacks.forEach(item => {
    
    
                    item.onResolved(data);
                });
            });
        }
        //reject 函数
        function reject(data){
    
    
            //判断状态
            if(self.PromiseState !== 'pending') return;
            //1. 修改对象的状态 (promiseState)
            self.PromiseState = 'rejected';// 
            //2. 设置对象结果值 (promiseResult)
            self.PromiseResult = data;
            //执行失败的回调
            setTimeout(() => {
    
    
                self.callbacks.forEach(item => {
    
    
                    item.onRejected(data);
                });
            });
        }
        try{
    
    
            //同步调用『执行器函数』
            executor(resolve, reject);
        }catch(e){
    
    
            //修改 promise 对象状态为『失败』
            reject(e);
        }
    }

    //then 方法封装
    then(onResolved,onRejected){
    
    
        const self = this;
        //判断回调函数参数
        if(typeof onRejected !== 'function'){
    
    
            onRejected = reason => {
    
    
                throw reason;
            }
        }
        if(typeof onResolved !== 'function'){
    
    
            onResolved = value => value;
            //value => { return value};
        }
        return new Promise((resolve, reject) => {
    
    
            //封装函数
            function callback(type){
    
    
                try{
    
    
                    //获取回调函数的执行结果
                    let result = type(self.PromiseResult);
                    //判断
                    if(result instanceof Promise){
    
    
                        //如果是 Promise 类型的对象
                        result.then(v => {
    
    
                            resolve(v);
                        }, r=>{
    
    
                            reject(r);
                        })
                    }else{
    
    
                        //结果的对象状态为『成功』
                        resolve(result);
                    }
                }catch(e){
    
    
                    reject(e);
                }
            }
            //调用回调函数  PromiseState
            if(this.PromiseState === 'fulfilled'){
    
    
                setTimeout(() => {
    
    
                    callback(onResolved);
                });
            }
            if(this.PromiseState === 'rejected'){
    
    
                setTimeout(() => {
    
    
                    callback(onRejected);
                });
            }
            //判断 pending 状态
            if(this.PromiseState === 'pending'){
    
    
                //保存回调函数
                this.callbacks.push({
    
    
                    onResolved: function(){
    
    
                        callback(onResolved);
                    },
                    onRejected: function(){
    
    
                        callback(onRejected);
                    }
                });
            }
        })
    }

    //catch 方法
    catch(onRejected){
    
    
        return this.then(undefined, onRejected);
    }

    //添加 resolve 方法
    static resolve(value){
    
    
        //返回promise对象
        return new Promise((resolve, reject) => {
    
    
            if(value instanceof Promise){
    
    
                value.then(v=>{
    
    
                    resolve(v);
                }, r=>{
    
    
                    reject(r);
                })
            }else{
    
    
                //状态设置为成功
                resolve(value);
            }
        });
    }

    //添加 reject 方法
    static reject(reason){
    
    
        return new Promise((resolve, reject)=>{
    
    
            reject(reason);
        });
    }

    //添加 all 方法
    static all(promises){
    
    
        //返回结果为promise对象
        return new Promise((resolve, reject) => {
    
    
            //声明变量
            let count = 0;
            let arr = [];
            //遍历
            for(let i=0;i<promises.length;i++){
    
    
                //
                promises[i].then(v => {
    
    
                    //得知对象的状态是成功
                    //每个promise对象 都成功
                    count++;
                    //将当前promise对象成功的结果 存入到数组中
                    arr[i] = v;
                    //判断
                    if(count === promises.length){
    
    
                        //修改状态
                        resolve(arr);
                    }
                }, r => {
    
    
                    reject(r);
                });
            }
        });
    }

    //添加 race 方法
    static race (promises){
    
    
        return new Promise((resolve, reject) => {
    
    
            for(let i=0;i<promises.length;i++){
    
    
                promises[i].then(v => {
    
    
                    //修改返回对象的状态为 『成功』
                    resolve(v);
                },r=>{
    
    
                    //修改返回对象的状态为 『失败』
                    reject(r);
                })
            }
        });
    }
}   

8. async and await

8.1 async function

  • The return value of the function is a promise object
  • The result of the promise object is determined by the return value of the async function execution

Same as then

async function main(){
    
    
    //1. 如果返回值是一个非Promise类型的数据
    // return 521;   //返回成功的promise对象状态

    //2. 如果返回的是一个Promise对象
    // return new Promise((resolve, reject) => {
    
    
    //     // resolve('OK');
    //     reject('Error');
    // });
    
    //3. 抛出异常
    throw "Oh NO"; //返回失败的promise对象状态
}

let result = main();

console.log(result);

8.2 await expression

  1. The expression on the right side of await is usually a promise object, but it can also be other values.
  2. If the expression is a promise object, await returns the value of the promise success
  3. If the expression is another value, use this value directly as the return value of await

Notice:

  • await must be written in the async function, but there can be no await in the async function
  • If the promise of await fails, an exception will be thrown, which needs to be caught and processed through try...catch.
async function main(){
    
    
    let p = new Promise((resolve, reject) => {
    
    
        // resolve('OK');
        reject('Error');
    })
    //1. 右侧为promise的情况(成功状态)
    // let res = await p;  //ok 
    
    //2. 右侧为其他类型的数据
    // let res2 = await 20;  //20

    //3. 如果promise是失败的状态
    try{
    
    
        let res3 = await p;
    }catch(e){
    
    
        console.log(e);
    }
}

main();

8.3 The difference between async await and callback function

/**
 * resource  1.html  2.html 3.html 文件内容
 */

const fs = require('fs');
const util = require('util');
const mineReadFile = util.promisify(fs.readFile);

//回调函数的方式
// fs.readFile('./resource/1.html', (err, data1) => {
    
    
//     if(err) throw err;
//     fs.readFile('./resource/2.html', (err, data2) => {
    
    
//         if(err) throw err;
//         fs.readFile('./resource/3.html', (err, data3) => {
    
    
//             if(err) throw err;
//             console.log(data1 + data2 + data3);
//         });
//     });
// });

//async 与 await
async function main(){
    
    
    try{
    
    
        //读取第一个文件的内容
        let data1 = await mineReadFile('./resource/1x.html');
        let data2 = await mineReadFile('./resource/2.html');
        let data3 = await mineReadFile('./resource/3.html');
        console.log(data1 + data2 + data3);
    }catch(e){
    
    
        console.log(e.code);
    }
}

main();

Reference https://www.bilibili.com/video/BV1GA411x7z1?p=1&vd_source=22466a8965f1e428d0c89e9b93d6d6b1

Guess you like

Origin blog.csdn.net/weixin_44157964/article/details/129525061
Recommended