javaScript之async-await及try...catch

  • 在ES7更新了基于promise的同步改写和异步改写,async 函数 和 await 来改造promise。

ES6 promise

  const p1 = function myp1() {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve("p1");
            }, 1000)
        })
    }
    const p2 = function myp2() {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve("p2");
            }, 1000)
        })
    }
    // 链式调用
    p1().then(res=>{
        console.log(res);  //p1
        return p2();
    }).then(res=>{
        console.log(res);  //p2
    }).catch(err=>{
        console.log(err);
    })

ES7 async-await及try…catch

async function asyncFn() {
    try {
        let res1 = await p1();
        console.log(res1);   //p1
        let res2 = await p2();
        console.log(res2)  //p2
    }catch(err){
        console.log(err);
    }
 
}
asyncFn(); 

通过async-await实现小方块运动运动一周

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            left: 0;
        }
    </style>
</head>
<body>
    <div class="box"></div>
</body>
<script>
    function move(ele, target, direction) {
        return new Promise((resolve) => {
            function fn() {
                let start = parseInt(window.getComputedStyle(ele, null)[direction]);
                let num = (target - start) / Math.abs((target - start));
                let speed = 5 * num;
                start += speed;
                if (Math.abs(target - start) < 5) {
                    resolve("运动完成");
                } else {
                    setTimeout(() => {
                        ele.style[direction] = start + "px";
                        // 递归
                        fn();
                    }, 20)
                }
            }
            fn();
        })
    }
    async function asyncFn(){
        let mydiv = document.querySelector(".box");
        try{
            await move(mydiv, 300, "left");
            await move(mydiv, 300, "top");
            await move(mydiv, 0, "left");
            await move(mydiv, 0, "top");
        }catch(err){
            console.log(err);
        }
    }
    asyncFn();
</script>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值