跳转到主要内容

主页内容

Promise详解

由 webadmin 发布于 阅读 81 次

1、准备

1.1、函数对象与实例对象

函数对象:将函数作为对象使用时,简称为函数对象。
实例对象:new 函数产生的对象,简称为对象。

<script>
       /**
         * 这里的Fn是一个函数
         * 
         */
        function Fn(){
        }
        const fn = new Fn();//这里的Fn是一个构造函数;fn是一个实例对象(简称:对象)
        console.log(Fn.prototype);//这里的Fn是一个函数对象。
        Fn.bind({a:1});//这里的Fn也是一个函数对象。这个操作是调用Fn这个函数对象的bind方法。
        $('#test');//这里的$是一个jQuery函数
        $.get('/test');//这里的$是一个jQuery函数对象
</script>

1.2、两种类型的回调函数

1.2.1、同步回调

理解:立即执行,完全执行完了才结束,不会放入回调队列中。
例子:数组遍历相关的回调函数、 Promiseexcutor 函数。

let arr = ["苹果","香蕉","橘子"];
arr.forEach((item)=>{
    //这是一个遍历的回调函数,是同步回调函数,不会放入队列中,立即执行完。
    console.log(item);
});
console.log("在forEach之后执行");//只有在forEach执行完以后,才会运行
1.2.2、异步回调
//2、异步回调函数
//异步回调函数,会放入队列中,将来执行。
setTimeout(()=>{
   console.log("timeout callback回调");
},0)
console.log("代码在setTimeout之后,执行在setTimeout之前");//在setTimeout之前就运行

理解:不会立即执行,会放入回调队列中将来执行。

例子:定时器回调 、 ajax回调 、 Promise的成功和失败的回调。

1.3、Js的error处理

1.3.1、常见的错误类型

Error: 所有错误的父类型。
ReferenceError:引用的变量不存在。
TypeError:数据类型不正确的错误。
RangeError:数据值不在其所允许的范围内。
SyntaxError:语法错误。

<script>
   //ReferenceError
   console.log(student);//报错:Uncaught ReferenceError: student is not defined
       
   //TypeError
   let b = null;
   b.xxx();//Uncaught TypeError: Cannot read properties of null (reading 'xxx')
   console.log(b.xxx);//Uncaught TypeError: Cannot read properties of null (reading 'xxx')
   //RangeError
   function Fn(){
     Fn();//Uncaught RangeError: Maximum call stack size exceeded
   }
   Fn();
   //SyntaxError
   let b = """";//Uncaught SyntaxError: Unexpected string
</script>
1.3.2、错误处理

捕获错误:try ...catch

<script>
	try{
    		let student;
    		console.log(student.xxx);
	}catch(error){
    		console.log(error.message);//Cannot read properties of undefined (reading 'xxx')
    		console.log(error.stack);//TypeError: Cannot read properties of undefined (reading 'xxx') at xxx.html:31:33
	}
	console.log("前面的代码出错以后,不影响后面代码运行");
</script>

抛出错误:throw error

<script>
	function Dosomething(){
    	if(Date.now() % 2 === 1){
    		console.log("当前时间是奇数,可以执行");
    	}else{
    		//抛出异常
    		throw new Error("当前时间是偶数。不能执行!");
    	}
    } 
    //Dosomething()中有抛出异常,在此处需要捕获一下异常
    try{
       Dosomething();
    }catch(error){
       console.error(error.stack);
    }
</script>
1.3.3、错误对象

message属性:错误相关信息。
stack属性:函数调用栈记录信息。

2、Promise的理解和使用

2.1、Promise理解

抽象的来说,Promise 是JS 中进行异步编程的新的解决方案。具体来说:

从语法上:Promise 是一个构造函数。
从功能上:promise 对象用来封装一个异步操作并可以获取其结果。

2.1.1、Promise的状态改变

(1)、由pendding变为resolved

(2)、由pendding变为rejected

说明:只有这2种,且一个 promise 对象只能改变一次,无论变为成功还是失败,都会有一个结果数据,成功的结果数据一般称为 vlaue,失败的结果数据一般称为 reason

2.1.2、Promise的基本流程
<script>
        //1、创建新的promise对象
        const p = new Promise((resolve, reject)=>{//执行器函数
            //2、执行异步操作任务
            setTimeout(()=>{
                const time = Date.now();//如果当前时间是偶数就代表成功,否则为失败
                if(time % 2 === 0){
                    //3.1、如果成功了,调用resolve(value)   
                    resolve("成功的数据,time = "+time);
                }else{
                    //3.2、如果失败了,调用reject(reason)
                    reject("失败的原因,time = "+time);
                }             
            },1000);
            
        });
        p.then(
            //接收得到成功的value数据 onResolved
            value => {
                console.log("成功的回调 ", value);
            },
            //接收得到失败的reason数据 onRejected
            reason => {
                console.log("失败的回调 ", reason);
            }
        );
</script>

2.2、为什么要用Promise

2.2.1、指定回调函数的方式更加灵活

纯回调函数: 必须在启动异步任务前指定  
promise: 启动异步任务 => 返回promise对象 => 给promise对象绑定回调函数(甚至可以在异步任务结束后指定)

2.2.2、支持链式调用, 可以解决回调地狱问题 

什么是回调地狱? 回调函数嵌套调用, 外部回调函数异步执行的结果是嵌套的回调函数执行的条件  
回调地狱的缺点?  不便于阅读 / 不便于异常处理  
解决方案? promise链式调用  
终极解决方案? async/await

function createAudioFileAsync() {}  
  
//执行函数  
function audioSettings() {}  
  
// 成功的回调函数  
function successCallback(result) {  
  console.log("声音文件创建成功: " + result);  
}  
// 失败的回调函数  
function failureCallback(error) {  
  console.log("声音文件创建失败: " + error);  
}  
  
/* 1.1 使用纯回调函数 */  
createAudioFileAsync(audioSettings, successCallback, failureCallback)  
  
/* 1.2. 使用Promise */  
const promise = createAudioFileAsync(audioSettings);  
//3秒后再绑定回调函数  
setTimeout(() => {  
  promise.then(successCallback, failureCallback);  
}, 3000);  
  
/*   
  2.1. 回调地狱  
  下一个回调函数依赖于上一个回调函数的执行结果,嵌套多层后,不便阅读  
 */  
doSomething(function(result) {  
  doSomethingElse(result, function(newResult) {  
    doThirdThing(newResult, function(finalResult) {  
      console.log('Got the final result: ' + finalResult)  
    }, failureCallback)  
  }, failureCallback)  
}, failureCallback)  
  
/*   
  2.2. 使用promise的链式调用解决回调地狱  
 */  
doSomething()  
  .then(function(result) {  
    return doSomethingElse(result)  
  })  
  .then(function(newResult) {  
    return doThirdThing(newResult)  
  })  
  .then(function(finalResult) {  
    console.log('Got the final result: ' + finalResult)  
  })  
  .catch(failureCallback)  
  
/*   
  2.3. async/await: 回调地狱的终极解决方案(ES7规范)  
 */  
async function request() {  
  try {  
    const result = await doSomething()  
    const newResult = await doSomethingElse(result)  
    const finalResult = await doThirdThing(newResult)  
    console.log('Got the final result: ' + finalResult)  
  } catch (error) {  
    failureCallback(error)  
  }  
}

2.3、如何使用Promise

2.3.1、Promise API
2.3.1.1、Promise构造函数: Promise (executor) {}  

(1)、executor函数: 同步执行 (resolve, reject) => {} 
(2)、resolve函数: 内部定义成功时调用的函数 value => {} 
(3)、reject函数:内部定义失败时调用的函数 reason => {} 
说明:executor会在Promise内部立即同步回调,异步操作在执行器中执行。

const p = new Promise((resolve, reject)=>{
            setTimeout(()=>{
                let time = Date.now();
                if (time % 2 === 0){
                    resolve("执行成功的数据");
                }else{
                    reject("执行失败的原因");
                }
            }, 1000);
})
2.3.1.2、Promise.prototype.then方法: (onResolved, onRejected) => {} 

(1)、onResolved函数:成功的回调函数  (value) => {} 
(2)、onRejected函数:失败的回调函数 (reason) => {} 
说明: 指定用于得到成功value的成功回调和用于得到失败reason的失败回调 返回一个新的promise对象。

p.then(
   value => {
      console.log('onResolved() ' + value);
   }
});
2.3.1.3、Promise.prototype.catch方法: (onRejected) => {}

onRejected函数:失败的回调函数 (reason) => {} 
说明:then()的语法糖, 相当于: then(undefined, onRejected)  

p.catch(reason => {
   console.error('onRejected()' + reason);
});
2.3.1.4、Promise.resolve方法: (value) => {}

value:成功的数据或promise对象 
说明:返回一个成功/失败的promise对象 

//1、需要产生一个值为1的promise对象的一般写法:
const pv1 = new Promise((resolve, reject)=>{
     resolve(1);
     //如果要求是失败的值为1的promise则执行
     //reject(1);
});
//2、使用语法糖写法产生一个值为2的promise对象
const pv2 = Promise.resolve(2);
//接收值
pv1.then(value=>{
    console.log(value);
});
pv2.then(value=>{
    console.log(value);
});
2.3.1.5、Promise.reject方法: (reason) => {}

reason:失败的原因 
说明:返回一个失败的promise对象 

//使用语法糖写法产生一个失败值为3的promise对象
const pv3 = Promise.reject(3);
//接收失败的值有2种写法
pv3.then(null, reason=>{
    console.error(reason);
});
//以下方法更简单
pv3.catch(reason=>{
   console.error(reason);
});
2.3.1.6、Promise.all方法: (promises) => {}

promises:包含n个promise的数组 
说明:返回一个新的promise,只有所有的promise都成功才成功,只要有一个失败了就直接失败。

//const pAll = Promise.all([pv1, pv2, pv3]);//执行完是失败的,因为pv3是失败的promise对象
const pAll = Promise.all([pv1, pv2]);//这个执行完是成功
pAll.then(
   //因为是多个值所以是values而不是value
   values => {
       //values是多个值,值的顺序取决于Promise.all([pv1, pv2])数组传递参数的顺序
       console.log("All onResolved:" +values);//输出:All onResolved:1,2
   },
   reason =>{
       console.error("All onRejected: "+reason);//输出:All onRejected: 3,因为3是pv3的失败原因
   }
);
2.3.1.7、Promise.race方法: (promises) => {}

promises:包含n个promise的数组 
说明:返回一个新的promise, 第一个完成的promise的结果状态就是最终的结果状态。

//const pRace = Promise.race([pv1, pv2, pv3]);//输出://输出:Race onResolved:1,因为第一个执行完成的异步操作返回的promise对象pv1是一个成功的状态
const pRace = Promise.race([pv3,pv1, pv2]);//输出:Race onRejected:3,因为第一个执行完成的异步操作返回的promise对象pv3是一个失败的状态
pRace.then(
      value  => console.log("Race onResolved:" +value),
      reason => console.error("Race onRejected:" +reason)
);
2.3.2、Promise的几个关键问题
2.3.2.1、如何改变Promise的状态

(1)、resolve(value):如果当前是pendding就会变为resolved
(2)、reject(reason):如果当前是pendding就会变为rejected
(3)、抛出异常:如果当前是pendding就会变为rejected

<script>
        const p = new Promise((resolve, reject)=>{
            //第1种情况
            //resolve(1);//pendding变为resolved
            //第2种情况
            //reject(2);//pendding变为rejected
            //第3种情况
            throw new Error("抛出异常");//抛出异常pedding变为rejected
        });
        p.catch(reason => {
            console.error(reason);//输出:抛出异常 抛出异常的失败抛出什么reason就是什么
        });
</script>
2.3.2.2、一个promise指定多个成功/失败回调函数,都会调用吗?

当promise改变为对应状态时都会调用。

以下两个then和一个catch都会调用。

<script>
        const p = new Promise((resolve, reject)=>{
            //第1种情况
            //resolve(1);//pendding变为resolved
            //第2种情况
            //reject(2);//pendding变为rejected
            //第3种情况
            throw new Error("抛出异常");//抛出异常pedding变为rejected
        });
        p.then(
            value => {
                console.log(value);
            },
            reason => {
                console.error('reason', reason);
            }
        );
        p.then(
            value => {
                console.log(value);
            },
            reason2 => {
                console.error('reason2', reason2);
            }
        );
        p.catch(reason => {
            console.error(reason);//输出:抛出异常 抛出异常的失败抛出什么reason就是什么
        });
</script>
2.3.2.3、改变promise状态和指定回调函数谁先谁后?

(1)都有可能,正常情况下是先指定回调再改变状态,但也可以先改状态再指定回调
(2)如何先改状态再指定回调?
          在执行器中直接调用resolve() / reject()
          延迟更长时间才调用then()
(3)什么时候才能得到数据?
如果先指定的回调,那当状态发生改变时,回调函数就会调用,得到数据。
如果先改变的状态,那当指定回调时,回调函数就会调用,得到数据。

<script>
        //常规:先指定回调函数,后改状态
        new Promise((resolve, reject)=>{
            setTimeout(()=>{
                resolve(1);//后改变状态(同时指定数据),异步执行回调函数
            },1000)//因为有延迟1000,所以会后执行
        }).then(//先指定回调函数,保存当前指定的回调函数
            value => {
                console.log(value);
            },
            reason => {
                console.error('reason', reason);
            }
        );
        //先改状态,后指定回调函数
        new Promise((resolve, reject)=>{
            resolve(1);//先改变状态(同时指定数据)
        }).then(//后指定回调函数
            value => {
                console.log('value2',value);
            },
            reason => {
                console.error('reason2', reason);
            }
        );
        //以下方式仍然是先改变状态,后指定回调函数,因为改变状态延迟了1000,而指定回调延迟了1100,指定回调延迟时间更长
        const p = new Promise((resolve, reject)=>{
            setTimeout(()=>{
                resolve(1);
            },1000)
        });
        setTimeout(()=>{
            p.then(
                value => {
                    console.log('value3',value);
                },
                reason => {
                    console.error('reason3', reason);
                }
            );
        },1100);
    </script>
2.3.2.4、promise.then()返回的新promise的结果状态由什么决定?

(1)、简单表达:由then()指定的回调函数执行的结果决定
(2)、详细表达:

  • 如果抛出异常,新promise变为rejected,reason为抛出的异常。
  • 如果返回的是非promise的任意值,新promise变为resolved,value为返回的值。
  • 如果返回的是另一个新promise,此promise的结果就会成为新promise的结果。
2.3.2.5、promise如何串连多个操作任务?
  • promise的then()返回一个新的promise,可以开成then()的链式调用
  • 通过then的链式调用串连多个同步/异步任务
new Promise((resolve, reject)=>{
            setTimeout(()=>{
                console.log("执行任务1(异步任务)");
                resolve(1);
            },1000)
        }).then(
            value => {
                console.log("任务1的结果为:",value);
                console.log("执行同步任务2(同步任务)");
                return 2;
            },
            reason => {
                console.error('onRejected1()', reason);
            }
        ).then(
            value => {
                console.log('任务2的结果:',value);
                //启动异步任务3
                return new Promise((resolve, reject) => {
                    setTimeout(()=>{
                        console.log('执行任务3(异步任务)');
                        resolve(3);
                    },1000)
                });
            },
            reason => {
                console.error('onRejected2()', reason);
            }
        ).then(
            value => {
                console.log("任务3的结果为:",value);
            },
            reason => {

            }
        );

执行结果:

2.3.2.5、promise异常穿透和中断promise链

(1)、promise的异常穿透

  • 当使用promise的then链式调用时,可以在最后指定失败的回调。
  • 前面任何操作出了异常,都会传到最后失败的回调中处理。

(2)、中断promise链

  • 当使用promise的then链式调用时,在中间中断,不再调用后面的回调函数。
  • 办法:在回调函数中返回一个pendding状态的promise对象。