1、promise初体验
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="js/jquery.js"></script>
<title>Title</title>
</head>
<body>
<button id="awards">抽奖</button>
<script>
function showrandom(x,y){
return Math.ceil(Math.random()*(y-x+1))+x-1
}
// $('#awards').click(()=>{
// setTimeout(function(){
// let random_number=showrandom(1,100)
// if (random_number<=30){
// alert('恭喜您,中奖了')
// }else{
// alert('很遗憾,您未中奖')
// }
// },2000)
// })
//resolve,reject都是函数类型的数据,resolve解决,reject拒绝或失败
const promise=new Promise((resolve,reject)=>{
setTimeout(function(){
let random_number=showrandom(1,100)
if (random_number<=30){
resolve()//将promise设置成成功状态
}else{
reject()//将promise设置成失败状态
}
},1000)
})
promise.then(()=>{
alert('恭喜您,中奖了')
},()=>{
alert('很遗憾,您未中奖')
})
</script>
</body>
</html>
2、promise传值到then中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="js/jquery.js"></script>
<title>Title</title>
</head>
<body>
<button id="awards">抽奖</button>
<script>
function show_random(x,y){
return Math.ceil(Math.random()*(y-x+1))+x-1
}
$('#awards').click(function(){
const promise=new Promise((resolve,reject)=>{
setTimeout(function(){
let random_value=show_random(1,100)
if (random_value<=30){
resolve(random_value)
}else{
reject(random_value)
}
},1000)
})
promise.then((value)=>{
alert('恭喜你,您中奖了,中奖号码是:'+value)
},(reason)=>{
alert('很遗憾,您未中奖,抽奖号码是:'+reason)
})
})
</script>
</body>
</html>
3、promise中封装文件操作
const fs=require('fs')
const promise=new Promise((resolve,reject)=>{
fs.readFile('./poem.txt',(err,data)=>{
if (err){
reject(err)
}else {
resolve(data)
}
})
})
promise.then((value)=>{
console.log(value.toString())
},(reason)=>{
console.log(reason)
})
4、promise中封装ajax操作(jquery封装ajax)
1、前端:index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./js/jquery.js"></script>
<title>Title</title>
</head>
<body>
<h3>发送ajax请求</h3>
<button id="send_ajax">发送ajax请求</button>
<script>
$('#send_ajax').click(function(){
const promise=new Promise((resolve,reject)=>{
$.ajax({
url