避免promise还是地狱回调写法

假如有3个函数,返回的都是一个promise,f2依赖f1返回的结果后才能执行,f3依赖f2返回的结果才能执行,这会导致回调地狱的写法,还是一层嵌套一层

 async function f1() {
      return 1
    }
    async function f2() {
      return 2
    }
    async function f3() {
      return 3
    }

    f1().then(res => {
      console.log(res);
      f2().then(res => {
        console.log(res);
        f3().then(res => {
          console.log(res);
        })
      })
    })

用以下这种写法就可以避免,在上一个回调里返回一个下一个要执行的函数,返回的也是promise

   f1()
      .then(res => {
        console.log(res);
        return f2()
      })
      .then(res => {
        console.log(res);
        return f3()
      }).then(res => {
        console.log(res);
      })

如果其中一个出错了 咋办?因为是链式调用,可以在最后面用catch捕获

  async function f1() {
      return 1
    }
    async function f2() {
      return Promise.reject(2)
    }
    async function f3() {
      return 3
    }
    f1()
      .then(res => {
        console.log(res);
        return f2()
      })
      .then(res => {
        console.log(res);
        return f3()
      }).then(res => {
        console.log(res);
      }).catch(e => {
        console.log('错误是', e);
      })

当然也可以用async await

 async function f1() {
      return 1
    }
    async function f2() {
      return Promise.reject(2)
    }
    async function f3() {
      return 3
    }
    async function test() {
      try {
        let res1 = await f1()
        console.log(res1);
        let res2 = await f2()
        console.log(res2);
        let res3 = await f3()
        console.log(res3);
      } catch (error) {
        console.log('错误是', error);
      }
    }
    test()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值