- 在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);
return p2();
}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
ES7 async-await及try…catch
async function asyncFn() {
try {
let res1 = await p1();
console.log(res1);
let res2 = await p2();
console.log(res2)
}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>