异步编程 - promise和async,await

146 阅读2分钟

promise的链式调用 ,解决回调地狱

<!-- 
  使用 Promise 进行定义接口:
  Promise 对象用于表示一个异步操作的最终完成 (或失败)及其结果值。
  它一个构造函数,所以可以通过 new 关键字来构建它,获取实例。
  在 Promise 中,分为了三种状态:
  1. 待定(pending): 初始状态,既没有被兑现,也没有被拒绝。
  2. 已兑现(fulfilled): 意味着操作成功完成。
  3. 已拒绝(rejected): 意味着操作失败。
  
  可以通过 promise 实例的 
  1. 成功:promise.then()
  2. 失败:promise.catch() 
  3. 结束:promise.finally()
  的三个方法,进行链式调用来解决回调地狱的问题。
 -->
<script>
  const isA = true
  const isB = true
  const isC = true
  const isD = true

  function A() {
    // 1. 创建 Promise 实例
    return new Promise((resolve, reject) => {
      // 2. 当前处于 【待定(pending)】 状态下
      console.log('执行 A 接口的逻辑')
      setTimeout(() => {
        if (isA) {
          // 3. 进入 【已兑现(fulfilled)】 状态下
          resolve('接口 A 执行完成')
        } else {
          // 4. 进入 【已拒绝(rejected)】 状态下
          reject('接口 A 执行失败')
        }
      }, 1000)
    })
  }

  function B() {
    return new Promise((resolve, reject) => {
      console.log('执行 B 接口的逻辑')
      setTimeout(() => {
        if (isB) {
          resolve('接口 B 执行完成')
        } else {
          reject('接口 B 执行失败')
        }
      }, 1000)
    })
  }

  function C() {
    return new Promise((resolve, reject) => {
      console.log('执行 C 接口的逻辑')
      setTimeout(() => {
        if (isC) {
          resolve('接口 C 执行完成')
        } else {
          reject('接口 C 执行失败')
        }
      }, 1000)
    })
  }

  function D() {
    return new Promise((resolve, reject) => {
      console.log('执行 D 接口的逻辑')
      setTimeout(() => {
        if (isD) {
          resolve('接口 D 执行完成')
        } else {
          reject('接口 D 执行失败')
        }
      }, 1000)
    })
  }

  // 获取 Promise 实例
  A()
    // 通过 .then 方法获取当前 Promise 的执行结果
    .then(res => {
      console.log(res);
      // 标记下一步进入 B 方法
      return B()
    })
    // 继续 .then 进行下一次的异步操作
    .then(res => {
      console.log(res);
      // 标记下一步进入 C 方法
      return C()
    })
    // 继续 .then 进行下一次的异步操作
    .then(res => {
      console.log(res);
      // 标记下一步进入 D 方法
      return D()
    })
    // 继续 .then 进行下一次的异步操作
    .then(res => {
      console.log(res);
      // 结束
    })

  1. promise 如何解决回调地狱

    通过 .then 的方式进行 链式调用

  2. Promise 的状态分为几种

    1. 待定(pending): 初始状态,既没有被兑现,也没有被拒绝。
    2. 已兑现(fulfilled): 意味着操作成功完成。
    3. 已拒绝(rejected): 意味着操作失败。
  3. 如何让 Promise 变成 已兑现(fulfilled)的状态,如何接收已兑现(fulfilled)的结果

    1. 通过 resolve 可以把 Promise 的状态,从 【待定(pending)】转变为 【已兑现(fulfilled)】
    2. 通过 promise实例.then 方法可以接收 已兑现(fulfilled) 的结果

async和await

Promise 的方案解决了 回调地狱 的问题,但是 Promise 又带来了新的问题,那就是:大量的链式调用,让我们的代码变得很长!

  // 使用 async 和 awiat 可以简化 Promise 的异步操作,把 Promise 的异步操作变为同步写法
  // async:标记一个函数为异步函数
  // await:标记当前操作为异步操作,await 关键字只能使用在被 【async标记的函数中】
  async function test() {
    const resA = await A();
    console.log(resA);
    const resB = await B();
    console.log(resB);
    const resC = await C();
    console.log(resC);
    const resD = await D();
    console.log(resD);
  }