HTML/Html-Javascript/33-异步代码同步化2.html

43 lines
1.1 KiB
HTML
Raw Normal View History

2023-05-01 19:37:40 +08:00
<!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>
<script>
// 定义一个Promise方法
function func() { // 正常 异常
return new Promise((resolve, reject) => {
setTimeout(() => {
let data = { n: "想不到吧, 我三秒后才出现, 你们抓不到我的" }
if (Math.random() > 0.5) {
resolve(data);
} else {
reject("完蛋了, bbq");
}
}, 1000);
});
}
// func().then() // 正常
// func().catch() // 异常
func()
.then(res => {
console.log(res);
})
.catch(e => {
console.error(e);
})
console.log("end");
</script>
</body>
</html>