【博学谷学习记录】超强总结,用心分享丨前端开发:Promise

Promise

一、promise的基本语法

1.创建 promise 对象

const p = new Promise((resolve,reject) => {
	//promise内部一般可以封装一个异步操作
	//resolve,reject是promise内部提供好给你的两个函数
	//成功调用resolve
	//失败调用reject
})

2.使用 promise 对象

p.then(res => {...})	//处理成功
 .catch(res => {...})	//处理失败

二、promise的三个状态

promise有三种状态:

  1. pending: 等待 (进行中)
    默认的状态
  2. fulfilled: 成功 (已完成)
    调用了 resolve 函数, promise的状态就会被标记成成功
  3. rejected: 失败 (拒绝)
    调用了 reject 函数, promise的状态就会被标记成失败
    注意: 一旦promise的状态发生变化, 状态就会被凝固

三、promise解决回调地狱问题

注意:如果有多个promise需要处理, 支持链式编程
promise链式编程:如果上一个 .then 中返回了一个新的 promise 对象,则可以交给下一个 .then 继续处理
在 Promise 的链式操作中如果发生了错误,可以使用 .catch 方法进行捕获和处理

 // =========================== Promise的链式调用 ===========================
    // then方法的返回值
    // 如果上一个.then() 方法中返回了一个新的Promise 实例对象,则可以通过下一个.then() 继续进行处理

    let p = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("结果1") // 状态 fulfilled 成功
      }, 2000);
    })

    // 获取到成功的结果
    p.then(res => {
      console.log("第一个then执行");
      console.log(res); // 结果1

      // 在then方法内返回了promise实例对象
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("结果2") // 状态 fulfilled 成功
        }, 2000)
      })
    }).then((res) => {
      console.log('第二个then执行')
      console.log(res) // 结果2
    })

四、Promise的常用静态方法

promise的常用静态方法:.all 和 .race

  1. Promise.all() 等待机制
    语法:Promise.all([ promise1, promise2, … ]).then( … )
    特征:发起并行的promise异步操作,会等待所有的异步操作都完成,才会走 .then
  2. Promise.race() 赛跑机制
    语法:Promise.race([ promise1, promise2, … ]).then( … )
    特征:发起并行的promise异步操作,只要任何一个异步操作完成,就会走 .then

五、封装创建promise对象

// =========================== 优化Promise解决回调地狱 ===========================
        // 将创建 promise 对象的过程,封装到一个函数中,需要promise对象,调函数即可

        function fn(color, time) {
            // color 就是成功的结果
            // time  延时时间

            // 记得将创建的promise实例对象给返回出去
            return new Promise((resolve, reject) => {
                setTimeout(function () {
                    resolve(color) // 状态 fulfilled 成功
                }, time)
            })
        }

        fn('is red', 2000)
            .then((res) => {
                console.log(res) // is red

                // return 新的promise 实例对象
                return fn('is yellow', 1000)
            })
            .then((res) => {
                console.log(res) // is yellow

                // return 新的promise 实例对象
                return fn('is green', 3000)
            })
            .then((res) => {
                console.log(res) // is green

                return fn('is ok1', 2000)
            })
            .then((res) => {
                console.log(res) // is ok1

                return fn('is ok2', 1000)
            })
            .then((res) => {
                console.log(res) // is ok2

                return fn('is ok3', 3000)
            })
            .then((res) => {
                console.log(res) // is ok3

            })

六、async和await 的基本使用

1.async用于修饰一个函数, 表示一个函数是异步的
如果async函数内没有await, 那么async没有意义的, 全是同步的内容
只有遇到了await开始往下, 才是异步的开始
2.await 要用在 async 函数中
3.await 后面一般会跟一个promise对象, await会阻塞async函数的执行, 直到等到 promise成功的结果(resolve的结果)
4.await 只会等待 promise 成功的结果, 如果失败了会报错, 需要 try catch

 // 使用 async await 解决回调地狱问题

        function fn(color, time) {
            // color 就是成功的结果
            // time  延时时间
            // 记得将创建的promise实例对象给返回出去
            return new Promise((resolve, reject) => {
                setTimeout(function () {
                    resolve(color) // 状态 fulfilled 成功
                }, time)
            })
        }


        // fn('is red', 2000)
        //     .then((res) => {
        //         console.log(res) // is red

        //         // return 新的promise 实例对象
        //         return fn('is yellow', 1000)
        //     })
        //     .then((res) => {
        //         console.log(res) // is yellow

        //         // return 新的promise 实例对象
        //         return fn('is green', 3000)
        //     })
        //     .then((res) => {
        //         console.log(res) // is green
        //     })


        // 使用 async await 来改写
         async function demo() {
             let color1 = await fn('is red', 2000)
             console.log(color1) // is red

             let color2 = await fn('is yellow', 1000)
             console.log(color2)

             let color3 = await fn('is green', 3000)
             console.log(color3)
         }
         demo()  // async 函数记得要调用,否则函数里面不执行
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值