promise专题01-初体验,promise传值到then中,封装文件操作,封装ajax,用一个函数封装promise,util.promisify,promise对象状态改变

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值