promise

Promise的三种状态?
    pending 等待中(promise封装的是一个异步操作,异步操作是需要时间的)
    fulfilled 成功 resolve()
    rejected 失败  reject()
状态只有两种情况:
    01 pending --> fulfllied
    02 pending --> rejected
状态只要发生改变了,就不会再次改变   




1
<!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>Document</title> 8 </head> 9 <body> 10 <script> 11 // Promise 单词表示承诺 12 // 是干嘛的? 是js中一种异步编程的解决方案(使异步函数可以同步执行),在没有promise之前,js是通过回调函数来实现异步编程的同步操作的 13 // Promise 解决了什么问题? 回到地狱,回调地狱是什么?回调函数层层嵌套 14 // promise的优势? 使异步函数可以同步的执行,解决了回调地狱的问题 15 // Promise是一个构造函数 16 // 理解:它是一个容器,内部分装了异步操作 17 // 参数:回调函数 18 // resolve表示then方法的回调函数 19 // 参数:lei hao a 会传递给data 20 21 22 // 成功 23 const p=new Promise(function(resolve,reject){ 24 // 异步操作成功就调用resolve 25 // 异步操作失败就调用reject 26 setTimeout(()=>{ 27 //参数:表示成功后,要传递的数据 28 resolve('lei hao a') 29 },2000) 30 }) 31 p.then(function(data){ 32 console.log('异步操作成功了',data) //两秒后输出 异步操作成功了 lei hao a 33 }) 34 35 36 37 38 39 // 失败 40 const L=new Promise(function(resolve,reject){ 41 // 异步操作成功就调用resolve 42 // 异步操作失败就调用reject 43 setTimeout(()=>{ 44 //参数:表示失败后:会将参数传递给err 45 reject('出错了') 46 },2000) 47 }) 48 L.then(function(data){ 49 console.log('异步操作成功了',data) 50 }).catch(function(err){ 51 console.log(err) 52 }) 53 54 </script> 55 </body> 56 </html>

 

 

 

<!DOCTYPE html>
<html lang="en">
<head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
</head>
<body>
      <script>
            function fn(){
                return new Promise((resolve)=>{
                    setTimeout(()=>{
                        console.log("第一")
                        resolve()
                    },2000)
                })
            }

            function fn2(){
                return new Promise((resolve)=>{
                    setTimeout(()=>{
                        console.log("第二")
                        resolve()
                    },2000)
                })
            }

            function fn3(){
                return new Promise((resolve)=>{
                    setTimeout(()=>{
                        console.log("第三")
                    },2000)
                })
            }


            // fn().then(fn2).then(fn3)
            (async function(){
                await fn()
                await fn2()
                await fn3()
            })()
      </script>
</body>
</html>

 

 

 

 

 

 

 

<!DOCTYPE html>
<html lang="en">
<head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
</head>
<body>
      <script>
            function liang(){
                  return new Promise(function(resolve){
                        var bang="亮儿的接力棒"
                        console.log("亮起跑...");
                        setTimeout(function(){
                              console.log("亮到达终点")
                              resolve(bang);
                        },3000)
                  })  
            }

            function ran(bang){
                  return new Promise(function(resolve){
                        console.log("ran然拿着"+bang);
                        setTimeout(function(){
                              console.log("然到达终点")
                              resolve(bang);
                        },5000)
                  }) 
            }

            function dong(bang){
                  return new Promise(function(resolve){
                        console.log("dong然拿着"+bang);
                        setTimeout(function(){
                              console.log("然到达终点")
                              resolve();
                        },8000)
                  })
            }


            // liang().then(ran).then(dong).then(function(){
            //      console.log("比赛结束")
            // })
            // ES7  啊sing靠  await  额为特是等待的意思,执行完才执行
            // 简化then()的时候用

            (async function(){
                  await  liang(); 
                  await  ran();
                  await  dong();
                  console.log("比赛结束") 
            })()

            /* 传参
            (async function(){
                  var bang=await  liang(bang);  // reutrn 回来的open(bang)
                  bang=await  ran(bang);
                  await  dong(bang);
                  console.log("比赛结束")
            })()
            */
            // 写一个async 函数自调,在里面  直接调用函数,在函数前加上 await就可以,await是等待完才执行, 
            // async和 await 配合 代替es6中的then(),更容易理解,更直观,更简化 
      </script>
</body>
</html>

 

 

 

<script>
      function fn (){
            return new Promise((resolve,reject)=>{
                  setTimeout(() => {
                        resolve('周浩')
                  }, 2000);
            })
      }
      // async 是用来修饰一个函数的 
      // async 要放在function 之前
      async function foo(){
            // await 关键字只能用在async函数中
            // await 关键字后面跟一个Promise对象
            // await 会等待Promise封装的异步操作执行完毕,才会执行后边的代码
            // res就是promise中 resolve的参数
           var res =await fn()
            console.log(res)//2000好秒后 输出   "周浩"
      }
      foo()
       
</script>

 

  <script>
      // 1  Promise.all([])   等所有请求都完成后,再执行后边的操作
        Promise.all([
              axios.get('http://localhost:3000/user'),
              axios.get('http://localhost:3000/student'),
              axios.get('http://localhost:3000/teacher'),
        ])
        .then((res)=>{
            // console.log(res)
        })




      // 2  只要有一个请求完成了,就执行一些操作
      Promise.race([
              axios.get('http://localhost:3000/user'),
              axios.get('http://localhost:3000/student'),
              axios.get('http://localhost:3000/teacher'),
      ])
      .then((res)=>{
            console.log(res)
      })


      

 // 3  Promise.resolve() 方法用来直接获取到一个成功的Promise对象
    Promise .resolve('123')
      .then(res => {
        console.log(res)
      })


//  4 直接获取到一个失败的Promise对象
    Promise.reject()

  </script>

 

案例  promise  和 async 配合 await 的使用

结果:点击按钮触发事件后,同步执行,先等5s输出 1,然后输出2

<!DOCTYPE html>
<html lang="en">
<head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
</head>
<body>
      <div id="btn" >按钮</div>
      <script>
            function ajaxyb (){
              return new Promise ((resove,reject)=>{
                  setTimeout (()=>{
                        console.log(1)
                        resove()
                  },5000)
              })
            } 
      var btn = document.getElementById('btn')
      btn.onclick= async function (){
            await ajaxyb()
            console.log(2)
      }
      </script>
</body>
</html>

 

案例2

    fetchPublicKey() {
      return new Promise((resolve) => {
        AuthorityApi.fetchPublicKey().then((res) => {
          this.publicKey = res.data
          resolve()
        })
      })
    },
    async submitForm() {
      await this.fetchPublicKey()
      await this.$refs.regForm.validate((valid) => {
        if (valid) {
          var tmpData = {
            account: this.regForm.user,
            passwordMap: SmUtils.encryptSm2(this.regForm.pass, this.publicKey),
            membersType: this.regForm.membersType,
            verifycode: this.regForm.verifycode,
            publicKey: this.publicKey
          }
          AuthorityApi.register(tmpData).then((res) => {
            this.$router.push({ path: 'MemberType',
              query: {
                membersId: res.data.membersId,
                membersType: this.regForm.membersType
              }})
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

 

 

 

const fs = require('fs')

// 使用Promise封装异步操作
function readFile(path) {
  const p = new Promise(function(resolve, reject) {
    fs.readFile(path, function(err, data) {
      if (err) {
        return reject(err)
      }

      resolve(data.toString())
    })
  })
  return p
}

// async 和 await 是异步编程的终极解决方案
async function fn() {
  // await 的返回值是 后面Promise 成功的结果,也就是 resolve 方法的参数
  try {
    const a = await readFile('./data/aa.txt')
    console.log(a)
  } catch (err) {
    console.log('出错了:', err)
  }

  const b = await readFile('./data/b.txt')
  const c = await readFile('./data/c.txt')
  const d = await readFile('./data/d.txt')

  console.log(b)
  console.log(c)
  console.log(d)
}

fn()

console.log('abc')

// Promise是可以无限调用  then 方法的
// 每一个后面的 then ,都可以获取到前一个 then 的返回值
/* 
readFile('./data/a.txt')
  .then(function(data) {
    console.log('a: ', data)
    return readFile('./data/b.txt')
  })
  .then(function(data) {
    console.log('b: ', data)
    return readFile('./data/c.txt')
  })
  .then(function(data) {
    console.log('c: ', data)
    return readFile('./data/d.txt')
  })
  .then(function(data) {
    console.log('d: ', data)
  })
 */
/* function readFile(path, callback) {
  fs.readFile(path, function(err, data) {
    callback(data)
  })
}
 */

  

 

 

     async showResult() {
        try{
          this.pictLoading = true  //显示
          this.showResultDialog = true
          setTimeout(async () => {
            const result =  await this.formatDataList()  //发送异步请求
            this.dialogData = result.finalResult
            this.pictLoading = false //隐藏
          }, 1000);
        }catch (err){
          console.log(err)
        }
      },

 

posted @ 2019-08-18 21:34  javascript9527  阅读(252)  评论(0编辑  收藏  举报