ES6之Promise承诺对象

Promise梳理
promise是构造函数,用于创建一个承诺对象,承诺对象主要用于封装异步操作。
作用:就是能把原来的回调写法分离出来,在异步操作执行完后,用链式调用的方式执行回调函数。(防止多层回调)
从表面上看,Promise只是能够简化层层回调的写法,而实质上,Promise的精髓是“状态”,用维护状态、传递状态的方式来使得回调函数能够及时调用,它比传递callback函数要简单、灵活的多。

promise存在三种状态:

承诺发起

承诺成功 resolved

承诺失败 rejected

1) 获取或者创建一个承诺对象

1 let promise = new Promise(function(resolve,reject){
2 })
3 
4 resolve 方法, 将承诺对象 pending -> resolved
5 reject 方法, 将承诺对象 pending -> rejected

2) 使用承诺对象

1、

Promise.prototype.then(successHandler[,errorHandler])
successHandler 当承诺成功的时候执行
errorHandler 当承诺失败的时候执行
一般不再then方法中添加errorHandler,而是将errorHandler放到catch中
返回值为当前promise实例

then方法是定义在原型对象Promise.prototype上的,也就是说,Promise 实例具有then方法。它的作用是为 Promise 实例添加状态改变时的回调函数。then方法的第一个参数是Resolved状态的回调函数,第二个参数(可选)是Rejected状态的回调函数。then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then方法后面再调用另一个then方法。如果使用两个then方法,第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。

getJSON("/post/1.json").then( 
    post => getJSON(post.commentURL)
 ).then( 
    comments => console.log("Resolved: ", comments), 
    err => console.log("Rejected: ", err) 
); 

2、

Promise.prototype.catch(errorHandler)
errorHandler 当承诺失败的时候执行

Promise.prototype.catch方法是.then(null, rejection)的别名,用于指定发生错误时的回调函数,一般来说,不要在then方法里面定义Reject状态的回调函数(即then的第二个参数)总是使用catch方法

var promise = new Promise(function(resolve, reject) { 
    reject(new Error('test')); 
});
 promise.catch(function(error) { 
    console.log(error);
 });

Promise 对象的错误具有“冒泡”性质,会一直向后传递,直到被捕获为止。也就是说,错误总是会被下一个catch语句捕获。

3、

Promise.prototype.finally(handler)
handler 不管承诺对象的状态变为什么样子,这个handler函数都会执行

finally方法用于指定不管Promise对象最后状态如何,都会执行的操作。它接受一个普通的回调函数作为参数,该函数不管怎样都必须执行。
下面是一个例子,服务器使用Promise处理请求,然后使用finally方法关掉服务器

server.listen(0).then(function(){
     // run test
 }) .finally(server.stop);    //关掉服务器

3) 高级特性
1.、

Promise.all([p1,p2,...])
将多个承诺对象合并为一个承诺对象,返回值为promise
Primese
.then((result)
=>{ //当所有的承诺都resolved的时候该回调函数才会执行 // result 为每个承诺对象返回值组成的一个数组   })   .catch(()=>{   //当有一个承诺对象rejected就会执行这个回调函数   }) 当查询出所有顾客信息以及订单信息后打开模态框

2.、

Promise.race([p1,p2,...])
将多个承诺对象合并为一个承诺对象,返回值为promise
promise
 .then((result)=>{
    //只要有一个承诺对象的状态变为resolved,就会执行该回调函数
  })
 .catch(()=>{
    //只要有一个承诺对象的状态变为rejected,就会执行该回调函数
  })

3.、

Promise.resolve(v)
  将v转换为承诺对象

4、

 Promise.rejected(v)
  返回一个状态为rejected的承诺对象

异步的解决方案:

传统ajax:

  let $ = {
    //使用回调
    get({url,success,error}){
      let xhr = new XMLHttpRequest();
      //设置请求行
      xhr.open("get",url);
      //设置请求头,标明请求体传递方式
      xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      //设置返回值
     xhr.responseType = "json";
     //设置请求体
     xhr.send();
     //监听机制
     xhr.onreadystatechange = function(){
       if(this.readyState === 4){
         if(this.status === 200){ 
           success(this.response);
         }else{
           error(this);
         }
     }
   }
 },
 $.get({
  url:"http://134.175.100.63:6677/customer/findAll",
   success:function(response){
     console.log(response)
   },
   error:function(xhr){
     console.log(xhr)
   }
 })

Promise封装ajax:

 //使用promise承诺对象
 get_promise(url){
   return new Promise(function(resolve,rejected){
     let xhr = new XMLHttpRequest();
     //设置请求行
     xhr.open("get",url);
     //设置请求头,标明请求体传递方式
     xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     //设置返回值
     xhr.responseType = "json";
     //设置请求体
     xhr.send();
     //监听机制
     xhr.onreadystatechange = function(){
       if(this.readyState === 4){
         if(this.status === 200){
           //请求成功
           resolve(this.response);
         }else{
           //请求失败
           rejected(this);
         }
       }
     }
   })
   }
 }
 get_promise(
   "http://134.175.100.63:6677/customer/findAll"
 ).then((response)=>{
   //当promise的状态由 pending -> resolved
   console.log("顾客信息:",response);
  }).catch((xhr)=>{
   //当promise的状态由 pengding -> rejected
   console.log(xhr);
   alert("异常")
 })
posted @ 2019-10-22 22:57  epoch丶  阅读(294)  评论(0编辑  收藏  举报