es6中promise 使用总结

 es6中promise实现ajax的例子

function getData(url){
        var pro = new Promise(function(resolve,reject){
            var xhr = null;
            try{
                xhr = new XMLHttpRequest()
            }
            catch(e){
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xhr.open("get",url);
            xhr.onreadystatechange=function (){
                if(xhr.readyState===4){
                    if(xhr.status===200){
                        resolve(xhr.response);
                    }else{
                        reject(new Error(xhr.status));
                    }
                }
            }
            xhr.send()
        })
        return pro;
    }
    getData("xxxx.url").then(function(data){
        console.log(data);
    },function(error){
        console.log(error);
    })

readyState

       0:已建立对象但没有send

       1:已经send对象正在载入

   2:载入完成

   3:解析接收到数据

   4:解析完成,可以response

 状态 status

      200ok

      302:文件暂时性转移

      304:资源在上次请求后没有修改

  500:服务器内部问题

 

Promise.all的使用

 

Promise.all([
  getApplicationManage(params),
     msgListConfig(),
     emailListConfig(),
     wechatListConfig(),
     getModuleManage(params)
  ]).then(function(values) {
      _this.applicationData = values[0].model;
      _this.msgConfigOptions = values[1].model;
      _this.emailConfigOptions = values[2].model;
      _this.wechatConfigOptions = values[3].model;
      let resData = values[4].model;
  }).catch(error => {
       console.log('error');
  }).finally(() => {
       this.loading = false;
       console.log('finally');
 });

 

 手写简易promise

promise对象状态改变只有两种可能,从pending改到fulfilled或者从pending改到rejected只要这两种情况发生,状态就不会再改变

 

   class myPromise {
        constructor(fn) {
          this.status = "pending"
          this.value = "";
          fn(this.resolve.bind(this),this.reject.bind(this))
        }
        resolve(val) {
          this.status = "fulfiled"
          this.value = val
        }
        reject(error) {
          this.status = "rejected"
          this.value = error
        }
        then(resolve, reject) {
          if (this.status == "fulfiled") {
            resolve(this.value)
          }
          if (this.status == "rejected") {
            reject(this.value)
          }
        }
      }

//使用 //打印出123 const p
= new myPromise((resolve, reject)=> { resolve("123") }) p.then((res)=>{ console.log(res) }, (error)=>{ console.log(error) } )

 

原文地址:https://www.cnblogs.com/zhaozhenzhen/p/12407966.html