Promise-入门笔记(基本认识及几个关键问题)

97 阅读9分钟

前置知识点

函数对象和实例对象

​ 函数对象:即是函数又可以当作对象来使用

​ 实例对象:简称对象

两种回调函数

​ 同步回调:函数中的回调函数执行完后,才会执行后续的操作,回调不会放入队列中

​ 异步回调:回调放入队列中,先执行后面的操作,等待回调执行并返回响应

​ 判断是同步还是异步:在执行函数后面写一个console.log进行输出判断是否先于回调执行,在回调之前打印则为异步回调

常见的内置错误

js中所有错误的父类型:Error

​ ReferenceError:引用错误,常见:引用的变量不存在(变量未定义

​ TypeError:类型错误,常见:xx is not a function/ can‘t read property xx of undefined

​ RangeError:范围错误,常见:递归调用自身函数导致栈溢出

​ SyntaxError:语法错误,会出现红色波浪线

错误处理(捕获与抛出)

​ 出现错误以后保证程序能够继续向下执行

​ 捕获错误:try。。。catch。。。,会对错误进行处理,会报错但是程序正常执行

​ 抛出错误:throw error,仅抛出错误,不对错误进行处理,程序中断

Promise

是什么

概念

​ 抽象:js中进行异步编程的新的解决方案(旧的解决方案:单纯的回调)

​ 具体: 1)从语法上来说,promise是一个构造函数

​ 如果是构造函数,一般是他的实例去做什么事。一般函数则用函数本身去做某事

​ 2)从功能上来说,promise对象用来封装一个异步操作并且可以获取其结果

promise的状态改变

​ 一共三种状态:pending、resolved、rejected

​ pending为初始状态,创建一个新的promise对象,该对象状态为pending

状态改变有且只有两种:

1)pending变为resolved

2)pending变为rejected

一个promise对象只能改变一次

​ 无论是成功还是失败,都会有一个结果数据

成功数据:value;失败数据:reason

promise的基本流程

​ new Promise(传参:执行器函数)→执行异步操作(回调函数)→成功:执行resolve();失败:执行reject() (未完成,懒得画图了)

promise的基本使用

const res = new Promise((resolve, reject) => {
  //执行器函数(同步回调函数),执行异步任务
  setTimeout(()=>{
    const time = Date.now() //如果当前时间是偶数则成功
    if(time % 2 === 0) {
      //如果成功,则调用resolve(value)
      resolve('成功的数据'+ time)
    } else {
      //如果失败,则调用reject(reason)
      reject('失败的数据'+ time)
    }
  },1000)
})
​
res.then(
  value=>{
    //接受得到成功的数据 onResolved函数
    console.log('成功的回调',value)
  },
  reason=>{
    //接受得到失败的数据   onRejected函数
    console.log('失败的回调',reason)
  }
)

为什么使用promise

一旦得到一个promise实例对象,说明启动了一个异步任务

1)promise指定回调函数的方式更加灵活

​ 单纯回调函数:需要先指定回调函数,再去执行异步任务

​ 使用promise执行异步任务:指定回调函数可以在执行异步任务之前,也可以在执行异步任务之后,甚至是在

任务结束之后,依然能够得到结果数据

2)promise支持链式调用,可以解决回调地狱的问题

​ 回调地狱:回调函数嵌套调用时不便于阅读也不便于异常处理,回调地狱会涉及到多个异步操作,而且是连续串联执行的,后面的异步任务都是以前一个异步任务的结果为条件的

​ 解决方案:promise链式调用

​ 回调地狱的终极解决方案:async/await

如何使用promise

API的含义:语法; 以及前后端交互的结果(常用api:resolve、reject、all、race)

几个关键问题

1. ​ 如何改变promise的状态

1)调用resolve:如果当前状态为pending则会变更为resolved

2)调用reject:如果当前状态为pending则会变更为rejected

3)抛出异常:如果当前是pending则会变为rejected

```
const res = new promise((resolve, reject) => {
  resolve(1) //Promise{1}  | 省略了<resolved>
  reject(2) //Promise{<rejected> 2}
  throw 3  //Promise{<rejected> 3}
})
console.log(res)
```

2. ​一个promise指定多个成功/失败的回调函数,都会调用吗?

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

```
const res = new Promise((resolve, reject)=>{
  const num = 5
  if (num > 5){
    resolve('true')
  }else {
    reject('false')
  }
})
​
res.then(
  value => {
    console.log('成功1'+ value)
  },
  reason => {
    console.log('失败1'+ reason)
  }
)
​
res.then(
  value => {
    console.log('成功2'+ value)
  },
  reason => {
    console.log('失败2'+ reason)
  }
)
​
//结果:失败1false   失败2false
//两个结果互不干扰,都受res的返回值的影响
```

3. ​改变promise状态和指定回调函数谁先谁后

1)都有可能,正常情况下是先指定回调函数再改变状态,但也可以先改变状态再指定回调函数

2)先改状态再指定

a、执行器中直接调用resolve()/reject() || 不使用异步回调函数调用resolve()/reject()

b、延迟更长时间再调用then

```
 
//  正常情况下执行器中为一个异步回调函数,若想实现先改变状态再指定回调,则需要延长更长时间调用then
const res = new Promise((resolve, reject)=>{
 setTimeout(()=>{
   resolve(1)   //  2、后改变状态,同时指定数据,异步执行回调函数
 },1000)
})
setTimeout(()=>{
  res.then(   //  1、先指定回调,保存当前指定的回调函数
    value => {
        console.log('成功1'+ value)    //   3、回调函数执行,得到数据
    },
    reason => {
        console.log('失败1'+ reason)    //   3、回调函数执行,得到数据
    }
)
},1100)
```

3)什么时候才能得到数据

a、如果先指定回调,那么当状态发生改变时,then中的回调函数就会调用,得到数据

```
new Promise((resolve, reject)=>{
 setTimeout(()=>{
   resolve(1)   //  2、后改变状态,同时指定数据,异步执行回调函数
 },1000)
}).then(   //  1、先指定回调,保存当前指定的回调函数
 value => {
    console.log('成功1'+ value)    //   3、回调函数执行,得到数据
  },
  reason => {
    console.log('失败1'+ reason)    //   3、回调函数执行,得到数据
  }
)
```

b、如果先改变状态,那么当指定回调时,then中的回调函数就会调用,得到数据

then中的回调函数为异步回调

```
new Promise((resolve, reject)=>{
   resolve(1)   //  1、先改变状态,同时指定数据
}).then(   //  2、后指定回调,异步执行回调函数
 value => {
    console.log('成功1'+ value)    //   3、回调函数执行,得到数据
  },
  reason => {
    console.log('失败1'+ reason)    //   3、回调函数执行,得到数据
  }
)
```

4. ​ promise.then()返回的新promise的结果状态由什么决定

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

``` 
new Promise((resolve, reject)=>{
  const num = 5
  if (num > 5){
    resolve('true')
  }else {
    reject('false')
  }
}).then(
  value => {
    console.log('成功1'+ value) 
  },
  reason => {
    console.log('失败1'+ reason)
  }
).then(   //
  value => {
    console.log('成功2'+ value)
  },
  reason => {
    console.log('失败2'+ reason)
  }
)
//第二个.then()的执行依赖于第一个.then()的执行结果
//上面的执行结果为 失败1false   成功2undefined
//失败是new Promise的reject执行,而成功2 undefined是因为第一个.then没有返回任何值,默认成功执行
```

2)详细表达:

a、如果抛出异常,新promise变为rejected,reason为抛出的异常

``` 
new Promise((resolve, reject)=>{
  resolve(1)   //  状态变为resolved
}).then(
  value => {   //  执行onResolved()
    console.log('成功1'+ value)  //  输出  ‘成功11’
    throw 2   //  抛出异常,则新promise变为rejected
  },
  reason => { console.log('失败1'+ reason) }
).then(   //  执行onRejected()
  value => { console.log('成功2'+ value) },
  reason => { console.log('失败2'+ reason) }  //输出  ‘失败22’
)
​
//结果: 成功11   失败22
```

b、如果返回的是非promise的任意值,新promise变为resolved,value为返回的值

``` 
new Promise((resolve, reject)=>{
  resolve(1)   //  状态变为resolved
}).then(
  value => {   //  执行onResolved()
    console.log('成功1'+ value)  //  输出  ‘成功11’
    return 2   //  返回值为非promise的任意值,则新promise变为resolved
  },
  reason => { console.log('失败1'+ reason) }
).then(   //  执行onResolved()
  value => { console.log('成功2'+ value) },  //输出  ‘成功22’
  reason => { console.log('失败2'+ reason) }  
)
​
//结果: 成功11   成功22
```

c、如果返回的是另一个新promise,此promise的结果就会成为新promise的结果

```
new Promise((resolve, reject)=>{
  resolve(1)   //  状态变为resolved
}).then(
  value => {   //  执行onResolved()
    console.log('成功1'+ value)  //  输出  ‘成功11’
    return Promise.resolve(2)   //  返回值为新promise,且新promise状态变为resolved
  },
  reason => { console.log('失败1'+ reason) }
).then(   //  执行onResolved()
  value => { console.log('成功2'+ value) },  //输出  ‘成功22’
  reason => { console.log('失败2'+ reason) }  
)
​
//结果: 成功11   成功22new Promise((resolve, reject)=>{
   resolve(1)   //  状态变为resolved
}).then(
   value => {   //  执行onResolved()
   console.log('成功1'+ value)  //  输出  ‘成功11’
   return Promise.reject(2)   //  返回值为新promise,且新promise状态变为rejected
 },
 reason => { console.log('失败1'+ reason) }
 ).then(   //  执行onRejected()
    value => { console.log('成功2'+ value) },
    reason => { console.log('失败2'+ reason) }  //输出  ‘失败22’
)
​
//结果: 成功11   失败22
```

5. ​ promise如何串联多个操作任务

1)promise的then()返回一个新的promise,可以看成then()的链式调用

2)通过then()的链式调用串联多个同步/异步任务

```
new Promise((resolve, reject)=>{
  console.log('执行任务1(异步)')
  resolve(1)   
}).then(
  value => {   
    console.log('任务1的结果'+ value)  
    console.log('执行任务2(同步)')
    return 2
  }
).then(   
  value => { 
    console.log('任务2的结果'+ value)  
    // 异步任务需要封装在一个新的promise中返回,因为异步队列中没有promise
    return new Promise((resolve, reject) => {
      setTimeout(()=>{
        console.log('执行任务3(异步)')
        resolve(3)
      },1000)
    })
  }
).then(
  value => { 
    console.log('任务3的结果'+ value)  
  }
)
​
//结果:
//执行任务1(异步)
//任务1的结果1
//执行任务2(同步)
//任务2的结果2
//执行任务3(异步)
//任务3的结果3
```

6. ​ promise异常穿透

1)当使用promise的then链式调用时,可以在最后指定失败的回调

2)前面任何操作出了异常,都会传到最后失败的回调中处理

```
new Promise((resolve, reject)=>{
  resolve(1)   
}).then(
  value => {   
    console.log('成功1'+ value)  
    return Promise.reject(2)   
  }
)
//如果第二个then中没有定义onRejected函数,那么第一个then返回了rejected状态的promise,下面的所有then都不再执行,直接去执行catch中的函数
//此时第二个函数中定义了onRejected函数,那么第一个then执行完后,去第二个then中,结果中的失败的回调2中的2,是第二个then中的reason
.then(   
  value => { console.log('成功2'+ value) } ,
  reason => {
    throw reason
  }
)
.then(   
  value => { console.log('成功3'+ value) } 
)
.catch(
  reason => {
    console.log('失败的回调' + reason)
  }
)
​
//结果:成功11   失败的回调2
​
```

7. ​ 中断promise链

1)当使用promise的then链式调用时,在中间中断,不再调用后面的回调函数

2)办法:在回调函数中返回一个pending状态的promise对象

``` 
new Promise((resolve, reject)=>{
  resolve(1)   
})
.then(
  value => {   
    console.log('成功1'+ value)  
    return 2
  }
)
.then(   
  value => { 
    console.log('成功2'+ value) 
    return new Promise(()=>{})  //中断promise链式调用,下面的链式调用均不执行
  }
)
.then(   
  value => { console.log('成功3'+ value) } 
)
.catch(
  reason => {
    console.log('失败的回调' + reason)
  }
)
​
//结果:成功11   成功22
```