Promise总结 | 青训营笔记

51 阅读7分钟

这是我参与「第四届青训营 」笔记创作活动的第2天

01准备

1.1区别实例对象与函数对象
  • 实例对象: new 函数产生的对象, 简称为对象
  • 函数对象: 将函数作为对象使用时, 简称为函数对象
const fn = new Fn() // Fn是构造函数  fn是实例对象(简称为对象)
console.log(Fn.prototype) // Fn是函数对象
$('#test') // jQuery函数
$.get('/test') // jQuery函数对象
1.2两种类型的回调函数
  • 同步回调:

    理解: 立即执行,完全执行完了才结束,不会放入回调队列中

    例子:数组遍历相关的回调函数 / Promise的excutor函数

  • 异步回调:

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

    例子:定时器回调 / ajax回调 / Promise的成功或失败的回调

1.3js的错误处理
1.3.1错误类型
  • Error: 所有错误的父类型

  • ReferenceError: 引用的变量不存在

  • TypeError: 数据类型不正确的错误

  • RangeError: 数据值不在其所允许的范围内

  • SyntaxError: 语法错误

// 常见的内置错误

// (1)TypeError引用的变量不存在
console.log(a);
console.log('ReferenceError之后的内容');

// (2)TypeError数据类型不正确的错误
let b;
console.log(b.xxx); // TypeError: b is undefined
let b = {};
console.log(b.xxx()); // TypeError: b.xxx is not a function

// (3)RangeError数据值不在引用范围内
function fun() {
  fun();
}
fun();  // RangeError: Maximum call stack size exceeded
// 火狐是InternalError

// (4)SyntaxError语法错误
console.log('''');  // SyntaxError: missing ) after argument list
1.3.2错误处理
  • 捕获错误: try ... catch

  • 抛出错误: throw error

1.3.3错误对象
  • message属性: 错误相关信息

  • stack属性: 函数调用栈记录信息

try {
  let b;
  console.log(x.xxx);
} catch (error) {
  console.log(error.message); // 错误相关信息
  console.log(error.stack);   // 函数调用栈记录信息
}

02Promise的理解与使用

2.1Promise是什么
2.1.1理解

抽象表达:Promise 是 JS 中进行异步编程的新的解决方案(旧的是谁?纯回调形式)

具体表达:

  • 从语法上说:Promise是一个构造函数
  • 从功能上说:Promise对象用来封装一个异步操作并可以获取其结果
2.1.2Promise状态的改变
  1. pending变为resolved
  2. pending变为rejected

Promise只有这两种状态变化,而且一个Promise对象只能改变一次,无论成功还是失败,都会有一个结果数据。成功的结果一般称为value,失败的结果一般称为reason

2.1.3Promise的基本流程

6promise_01.png

2.1.4Promise的基本使用
// 1.创建一个新的promise对象
const p = new Promise((resolve, reject) => {  // 执行器函数
  // 2.执行异步操作
  setTimeout(() => {
    const time = Date.now();
    if (time % 2) {
      // 3.1如果成功了,调用resolve(value)
      resolve('成功的数据' + time);
    } else {
      // 3.2如果失败了,调用reject(reason)
      reject('失败的数据' + time);
    }
  }, 0);
});

p.then(
  value => {  // 接收得到成功的value数据  onResolved
    console.log('成功的回调执行了', value);
  },
  reason => { // 接受得到失败的reason数据 onRejected
    console.log('失败的回调执行了', reason);
  }
)
2.2为什么要用Promise
  1. 指定回调函数的方式更加灵活

    旧的:必须在启动异步任务之前指定;Promise可以在异步任务结束后指定,也可以指定多个

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

    地狱回调问题:回调函数嵌套调用,外部回调函数异步执行的结果是嵌套的回调函数的执行条件;

    缺点是不便于阅读、不便于异常处理

    解决方案:Promise链式调用

    终极解决方案:async和await

    // 地狱回调
    doSomething(function (result) {
      doSomethingElse(result, function (newResult) {
        doThirdThing(newResult, function (finalResult) {
          console.log('Got the final result: ' + finalResult)
        }, failureCallback)
      }, failureCallback)
    }, failureCallback)
    
    // 使用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)
    
    // async/await: 回调地狱的终极解决方案
    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.1API
  1. Promise构造函数: Promise (excutor) {}

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

  2. Promise.prototype.then方法: (onResolved, onRejected) => {}

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

  3. Promise.prototype.catch方法:(onRejected) => {}

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

  4. Promise.resolve方法:(value) => {}

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

  5. Promise.reject方法:(reason) => {}

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

  6. Promise.all方法:(promises) => {}

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

  7. Promise.race方法:(promises) => {}

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

2.3.2Promise的几个关键问题
  1. 如何改变Promise的状态

    • resolve(value):如果当前是pendding就会变为resolved
    • reject(reason):如果当前是pendding就会变为rejected
    • 抛出异常:如果当前是pendding就会变为rejected
  2. 一个promise指定多个成功或失败回调函数,都会调用吗?

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

    const p = new Promise((resolve, reject) => {
      // resolve(1) // promise变为resolved成功状态
      // reject(2) // promise变为rejected失败状态
      // throw new Error('出错了') // 抛出异常, promse变为rejected失败状态, reason为抛出的error
      throw 3 // 抛出异常, promse变为rejected失败状态, reason为抛出的3
    })
    p.then(
      value => { },
      reason => { console.log('reason', reason) }
    )
    p.then(
      value => { },
      reason => { console.log('reason2', reason) }
    )
    //reason 3
    //reason2 3
    
  3. 改变promise状态和指定回调函数谁先谁后?

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

    如何先改状态再指定回调?

    • 在执行器中直接调用resolve()/reject()
    • 延迟更长时间才调用then()

    什么时候才能得到数据?

    • 如果先指定的回调,那当状态发生改变时,回调函数就会调用,得到数据
    • 如果先改变的状态,那当指定回调时,回调函数就会调用,得到数据
    // 常规: 先指定回调函数, 后改变的状态
    new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(1) // 后改变的状态(同时指定数据), 异步执行回调函数
      }, 1000);
    }).then(      // 先指定回调函数, 保存当前指定的回调函数
      value => { },
      reason => { console.log('reason', reason) }
    )
    
    // 先改状态, 后指定回调函数
    new Promise((resolve, reject) => {
      resolve(1)  // 先改变的状态(同时指定数据)
    }).then(      // 后指定回调函数, 异步执行回调函数
      value => { console.log('value2', value) },
      reason => { console.log('reason2', reason) }
    )
    
  4. promise.then()返回的新promise的结果状态由什么决定?

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

    详细表达:

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

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

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

    promise.then()返回的新promise,then中的value是具体的值,注意区分

    new Promise((resolve, reject) => {
        resolve(1);
    }).then(
        value => {
            console.log(value);
            return 123;
        }
    ).then(
        value => {
            console.log(value);
        }
    )
    //1 123
    
  5. promise如何串连多个操作任务?

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

    通过then的链式调用串连多个同步或异步任务

  6. promise异常穿透

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

    new Promise((resolve, reject) => {
        resolve(1);
    }).then(
        value => {
            console.log(value);
            return 2;
        }
        // then中不写onRejected相当于加上这句:
        reason => { throw reason }
    ).then(
        value => {
            console.log(value);
            throw 3;	// 抛出错误
        }
    ).catch(
        reason => {
            console.log('抓住你了', reason);
        }
    )
    // 1
    // 2
    // 抓住你了 3
    
  7. 如何中断promise链?

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

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

    return new Promise(() => { })