<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button onclick="btnClick()">点击</button>
<script>
let p = (params) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (params > 5) {
resolve("运行成功");
} else {
reject("运行失败");
}
}, 1000);
});
};
/**
* 正常使用:
* 1、会先执行 console.log(1)
* 2、然后执行 p(num)
*/
function btnClick() {
let num = Math.random() * 10;
p(num)
.then((res) => {
console.log(res);
})
.catch((e) => {
console.log(e);
});
console.log(1)
}
/**
* async...await方式:
* 1、返回成功,则继续执行 console.log(1)
* 2、返回失败,则执行 console.log(2)
*/
// async function btnClick() {
// let num = Math.random() * 10;
// try {
// await p(num);
// console.log(1);
// } catch (error) {
// console.log(2);
// }
// }
</script>
</body>
</html>