ES6中的promise对象及其应用

目录

一、promise承诺对象

二、使用promise封装ajax或者axios

三、promise静态方法

1.Promise.all()

2.Promise.any()

3.Promise.race()

4.Promise.allSettled()

5.Promise.resolve()

6.Promise.reject()

四、防抖

五、节流

六、事件循环


一、promise承诺对象

  是一个容器,存放着将来才会执行代码,异步编程解决方法 

  实例方法可以处理异步请求

  实例状态:1.pending 未操作/进行中
                    2.fullfilled 已成功-------resolve
                    3.rejected 已失败---------reject

  实例方法:
          1.then(()=>{})  当promise实例状态为fullfilled时候执行then回调函数
          2.catch(()=>{}) 当promise实例状态为rejected时候执行catch回调函数
          3.finally(()=>{}) promise实例状态为任何执行回调函数
  Promise(参数:(resolve,reject)=>{
    resolve---promise实例状态为fullfilled执行回调函数--------请求成功执行回调函数
    reject ---promise实例状态为rejected执行回调函数 ---------请求失败执行回调函数
  })构造函数创建实例对象

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    /**
     * promise 承诺对象 存放着将来才会执行得代码 主要获取异步操作得消息 可以对异步操作成功与否
     * 使用特定回调函数进行处理 异步编程解决方案 
    */
    let promise = new Promise((resolve,reject)=>{
      // resolve回调函数 表示promise实例为fullfilled得回调函数  请求成功执行得回调函数
      // reject回调函数 表示promise实例为rejected得回调函数 请求失败执行回调函数
      // 模拟异步请求
      if(3>2){
        resolve('请求成功')
      }else{
        reject('请求失败')
      }
    });
    // 当promise实例状态发生改变 可以调用实例方法进行处理 
    // then方法promise实例状态为fullfilled执行回调函数
    // catch方法当promise实例状态为rejected执行回调函数
    // finally 无论实例状态成功与否都会执行回调函数


    promise.then((res)=>{
      // resolve 由then方法第一个回调函数提供得
      console.log(res)
    }).catch((error)=>{
      // reject 由catch方法回调函数提供
      console.log(error)
    }).finally(()=>{
      console.log('最终执行')
    })


    // then可以接收两个回调函数 
    promise.then((res)=>{
      // 第一个回调函数表示promise实例状态为fullfilled执行回调函数
      console.log(res,'1111')
    },(error)=>{
      // 第二个回调函数表示promise实例状态为rejected执行回调函数----reject
      console.log(error,'2222')
    })
    console.log(Promise,'33333')
  </script>
</body>
</html>

二、使用promise封装ajax或者axios

  封装工厂函数,得到一个基于promise的ajax请求

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    function getPromise(method,url,data,params){
      // data---post携带参数 params---get请求携带参数
      return new Promise((resolve,reject)=>{
        var xhr = new XMLHttpRequest();
        xhr.open(method,url);
        xhr.send();
        xhr.onreadystatechange = function(){
          if(xhr.readyState===4){
            if(xhr.status===200){
              resolve(xhr.response)
            }else{
              reject(xhr.responseText)
            }
          }
        }
      })
    }
    let p1 = getPromise('get','自己的服务器地址');
    let p2 = getPromise('get','自己的服务器地址');
    console.log(p1,p2);
    p1.then(res=>{
      console.log(JSON.parse(res),'111')
    })
    p2.then(res=>{
      console.log(JSON.parse(res),'222')
    });

  </script>
</body>
</html>

三、promise静态方法

1.Promise.all()

        参数:实现了迭代器接口数据结构 数组[多个promise实例]
        得到一个promise实例对象 所有实例请求成功或者所有实例都为fullfilled 实例才是fullfilled

2.Promise.any()

        参数:实现了迭代器接口数据结构 数组[多个promise实例] 
        得到一个promise实例对象 任意一个实例请求成功或者实例变为fullfilled 实例就是fullfilled

3.Promise.race()

        参数:实现了迭代器接口数据结构 数组[多个promise实例] 
        赛跑 那个实例状态先变为fullfilled 就返回哪一个实例

4.Promise.allSettled()

        参数:实现了迭代器接口数据结构 数组[多个promise实例] 
        对每一个promise实例都进行处理

5.Promise.resolve()

        得到状态发生改变(fullfilled)promise实例

6.Promise.reject()

        得到状态发生改变(rejected)promise实例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
   let res =  Promise.all([p1,p2]);
   let res =  Promise.any([p1,p2]);
   let res =  Promise.race([p1,p2]);
   let res =  Promise.allSettled([p1,p2]);
   console.log(res);
  res.then(res=>{
    console.log(res)
  })
  console.log(Promise.resolve(),'111');
  console.log(Promise.reject(),'222');
</script>
</body>
</html>

四、防抖

  目的:为了优化高频率js事件得手段

  在一定时间内,事件一直频繁触发,会重新计算时间,直到超过设定时间,函数才会执行最后一次

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.js"></script>
</head>

<body>
  <input type="text">
  <script>
    console.log(_);
    var input = document.querySelector('input');
    // 监听输入框事件
    // input.oninput = _.debounce(function(){
    //   console.log(this.value)
    // },1000)

    //zhangsan 
    let timer;
    input.oninput = function(){
      if(timer){
        clearTimeout(timer)
      }
      var that = this;
      timer = setTimeout(function(){
        console.log(that.value)
      },1000)
    }



    input.oninput = debounce(function () {
      console.log(this.value)
    }, 1000)
    // 封装防抖函数 
    function debounce(callback, wait) {
      let timer;
      return function () {
        if (timer) {
          clearTimeout(timer)
        }
        var that = this;
        timer = setTimeout(function () {
          console.log(this)
          callback.call(that);
        }, wait)
      }
    }
  </script>
</body>

</html>

五、节流

  目的:为了优化高频率js事件得手段

  在一定时间内,事件一直频繁触发,会每隔设定时间函数才会执行一次

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.js"></script>
  <style>
    body {
      height: 3000px;
    }
  </style>
</head>

<body>
  <script>
    // window.onscroll = _.throttle(function () {
    //   console.log('我正在滚动')
    // }, 1000);

    window.onscroll = throttle(function () {
      console.log('我正在滚动')
    }, 1000);
    
    function throttle(callback, wait) {
      let id;
      return function () {
        if (!id) {
          id = setTimeout(function () {
            callback();
            id = null;
          }, wait)
        }
      }
    }
  </script>
</body>

</html>

六、事件循环

        js单线程语言,同一时间只能做一件事情,异步代码会被放在任务队列中等待执行,先执行同步任务,再执行异步任务。

什么是同步任务?什么是异步任务?

  js任务分为同步任务和异步任务:

        不耗时任务同步任务 耗时任务就是异步任务 

  异步任务又分为宏任务和微任务

  宏任务:定时器setTimeout  间歇调用 I/O操作 文件读取(fs.readFile()) 网络请求

  微任务:promise.then catch finally  async await写在后面代码相当于创建微任务

//setTimeout第二个参数可以省略,默认为0     //2 4 5 7 10 3 8 6 1 9 
setTimeout(function () {
  console.log('1');
});                             
// new Promise((resolve,reject)=>{})
new Promise(function (resolve){
  console.log('2');
  resolve();
}).then(function () {
  console.log('3');
});
console.log('4');
async function async1() {
  console.log(5);
  const result = await async2();
  console.log(6);
}
async function async2() {
  console.log(7);
}
Promise.resolve().then(() => {
  console.log(8);
});
setTimeout(() => {
  console.log(9);
});
async1();
console.log(10); 

    //                            主线程:      异步队列:读取文件 fs.readFile() 网络请求
    //                                   打印2      微任务:打印3     宏任务:定时器打印1 
    //                                   打印4              打印8            定时打印9
    //                                   打印5              打印6
    //                                   打印7  
    //                                   打印10 3 8 6 1 9

  • 23
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值