Promise

一. promise的基本概念

回调地域

​ 多层回调函数的相互嵌套,就形成了回掉地狱。

  • 缺点:代码耦合性太强,代码维护难度大,冗余代码,可读性变差
1.promise是一个构造函数
  • 可以创建promise的实例

     const p =mew Promise()
    
  • new出来的Promise实例对象,代表一个异步操作

2.Promise.prototype上包含一个.then()方法
  • image-20221003085308711
  • 都可以通过原型链访问到 .then()的方法, p.then()
  1. .then()方法用来预先指定成功和失败的回调函数
    • p.then(成功的回调函数,失败的回调函数)
      p.then(res=>{},err=>{})
      
  • 调用 .then()方法时,成功的回调函数是必选的,失败的回调函数是可选的。
  1. .then()方法的新特性
    • 如果上一个 .then()方法中,返回一个新的Promise实例对象则可以通过下一个 .then()方法链式调用,就解决了回调地狱的问题。
  • image-20221003092731913
  1. .catch()方法,在Promise的链式调用中如果发生错误,可以使用 Promise.prototype.catch()方法进行捕获和处理。
    • 注意:当.catch位于最后时,前面的代码发生错误时,就会被catch捕获,导致前面的.then方法无法执行,所以要让前面的.then方法执行,可以catch放在前面,提前捕获。
  • thenFs
      .readFile("./files/11.txt", "utf8")
      .catch((err) => {
        console.log(err.message);
      })
      .then((r1) => {
        console.log(r1);
        return thenFs.readFile("./files/2.txt", "utf8");
      })
      .then((r2) => {
        console.log(r2);
        return thenFs.readFile("./files/3.txt", "utf8");
      })
      .then((r3) => {
        console.log(r3);
      });
    
  1. Promise.all()方法会发起并行的Promise异步操作,等所有的的异步操作全部结束后才会执行下一步的.then操作(等待机制)。
    const promiseArr = [
      thenFs.readFile('./files/3.txt', 'utf8'),
      thenFs.readFile('./files/2.txt', 'utf8'),
      thenFs.readFile('./files/1.txt', 'utf8'),
    ]
    Promise.all(promiseArr).then(result => {
      console.log(result)
    })
    
    • 最后结果的顺序就是数组定义时的执行顺序,执行结果也是对应的数组。
  2. Promise.race()方法会发起并行的 Promise 异步操作,只要任何一个异步操作完成,就立即执行下一步的.then 操作(赛跑机制)。
    Promise.race(promiseArr).then(result => {
      console.log(result)
    })
    
  3. 练习:封装一个异步读文件的方法。
    import fs from 'fs'
    function getFile(fpath) {
      return new Promise(function (resolve, reject) {  //两个回调函数分别接受成功和失败的情况
        fs.readFile(fpath, 'utf8', (err, dataStr) => {
          if (err) return reject(err)  //调用失败的回调函数
          resolve(dataStr)     //调用成功的回调函数
        })
      })
    }
    
    getFile('./files/11.txt')
      .then((r1) => {
        console.log(r1)
      })
      .catch((err) => console.log(err.message))   //捕获整个过程中失败的报错
    

二. async/await

  • image-20221003112227595

如果某个方法的返回值是一个Promise实例对象,那么在方法前用await进行修饰,那么返回的不再是一个Promise对象,而是对应成功的返回值(用变量r1接收的,就是文件的内容),内部使用了await修饰后,外部方法前一定要用async进行修饰。

  • async/await 的使用注意事项

① 如果在 function 中使用了 await,则 function 必须被 async 修饰

② 在 async 方法中,第一个 await 之前的代码会同步执行,await 之后的代码会异步执行

三. Promise实现ajax的请求

利用Promise实现的ajax的方式很多,但是核心内容是将ajax成功和失败后得返回结果抛出,通过then方法在外部使用。当发生嵌套时,内部继续调用promise_ajax方法,外部可以链式调用返回结果,保证请求顺序的同时,避免回调地域。

参考代码,不唯一

const promise_ajax(params) {
      let send = new Promise((resolve, reject) => {
                $.ajax({
                    url: params.url,
                    data: params.data,
                    type: params.type,
                    success: function (e) {
                        console.log(e)
                        resolve(e)    //  
                    },
                    error: function(e) {
                        reject(e);  //  
                    },
                    complete: function (e) {
                        console.log(e)
                    }
                })
            });
     return send;  //返回的是个Promise对象
}


promise_ajax({
		//接口地址
        url: global_domain + '/interface/Resource/uploadBySuffixName?jsonVar=get_grade_list&token='+global_token,
        //请求参数
        data: {school_id: this.school_val},
        //请求方式
        type: 'GET'
}).then((e) => {
		//成功回调
        console.log(e)
}).catch((e) => {
		//失败回调
        console.log(e)
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值