js await/async 和promise的try catch 区别与坑

13 篇文章 0 订阅

结论说前

推荐使用async和await,语法看起来更简洁和顺眼

区别

pormise的then 和catch不会阻塞后面的代码

       console.log('.then代码的之前');
        api()
            .then((e) => {
                console.log('.then执行了');
            })
        console.log('.then代码的之前');

在这里插入图片描述

而 await/async 并不会阻塞后面,而且比promise读起来更顺

    async function test() {
        console.log('.await代码的之前');
        data = await api()
        console.log('.await代码的之后');
    }

在这里插入图片描述

一些坑

1 使用pormise时候,用回调拿返回值,而不是return,这个最容易犯错
错误的使用return拿返回值

    function getData(success) {
        let res=null
        api()
            .then((e) => {
                res=e
            })
        return res
    }
    let res= getData()

    setTimeout(()=>{
        console.log(res);
    },2000)

在这里插入图片描述

应该使用回调函数

    function getData(success) {
        let res=null
        api()
            .then((e) => {
                success(e)
            })
    }
    let res=null
    getData((e)=>{res=e})

    setTimeout(()=>{
        console.log(res);
    },2000)

在这里插入图片描述
**2 只要被async声明了,那么这个函数的返回值就自动变成了Promise,意思就是这个函数可能过一会才会有值,函数内return的值会被自动resolve,thorw和任何错误会被自动reject **

 async function test() {
        return 1
    }
    test()
        .then((e) => {
            console.log('e', e);  //e 1
        })
        .catch((e) => {
            console.log('error', e);
        })

在这里插入图片描述

    async function test() {
        throw '出错啦'
    }
    test()
        .then((e) => {
            console.log('e', e);
        })
        .catch((e) => {
            console.log('error', e);
        })

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值