浅谈promise用es5实现

作为新人第一次撸博客,写的不好 多多包涵

 由于JavaScript所有的代码都是单线程执行的 所以es6的时候出现了promise

 promise作为es6的异步操作构造函数有all、reject、resolve这几个方法,其原型上then、catch等方法;其有三种状态分别为

pending进行中,resolve已完成,reject失败

1.接下来我们进入正题,这篇博客内容主要是为了更加深刻的理解promise的原理:

//那new一个把
var test = new Promise(function(resolve, reject){
        resolve('数据');
});

  promise作为一个构造函数,接收的参数是个函数,传入两个参数(resolve,reject)分别表示异步操作执行成功和失败的回调;

  resolve把状态从pending变成resolve,reject把状态从pending变成reject

  一般我们用promise的时候是包在一个函数中,在需要的时候去调用运行它:

function Async(){
    var test = new Promise(function(resolve,reject){
         resolve("成功返回数据")
    })
    return test;
}
Async()

 接下来我们就可以调用它:

Async().then(function(res){
    console.log(res)
//....
//可以对传过来的数据进行一系列操作 })

你还可以不断地then进行回调进行链式操作用法:

promise成功解决了之前es5的回调地狱

用代码来展示下promise的精髓:

function Async1(){
    var p = new Promise(function(resolve, reject){
            resolve('随便什么数据1');
    });
    return p;            
}
function Async2(){
    var p = new Promise(function(resolve, reject){
            resolve('随便什么数据2');
    });
    return p;            
}
function Async3(){
    var p = new Promise(function(resolve, reject){
            resolve('随便什么数据3');
    });
    return p;            
}


Async1()
.then(function(data){
    console.log(data);
    return Async2();
})
.then(function(data){
    console.log(data);
    return Async3();
})
.then(function(data){
    console.log(data);
});

//接下来可以清楚的看到:
//
随便什么数据1
// 随便什么数据2
// 随便什么数据3
 

2.promise的用法已经介绍了,接下来我们来用es5实现promise:

function promise (fn) {
           if (typeof this !== 'object') { 
              throw new TypeError('Promises must be constructed via new');
           }
           if (typeof fn !== 'function') {
               throw new TypeError('Promise constructor\'s argument is not a function');
            }
            this.state = "pending"; //定义状态
            this.msg="";
            var process=arguments[0];
            var that=this;
            process(function(){
                that.state="resolve"
                that.msg=arguments[0]
            },function(){
                that.state="reject"
                that.msg=arguments[0]
            })
            return this
      }
      promise.prototype.then=function(){
          constructor:promise
          if(this.state == "resolve"){
              arguments[0](this.msg)
          }else if(this.status=='reject'&&arguments[1]){
              arguments[1](this.msg)
          }
          promise=new this.constructor(function (resolve,reject) {resolve("2")}) //每次调用then之后重新返回一个新的promise实例进行下一步then的调用
        //   console.log(this)
        //   console.log(promise)
          return promise
      }
    var mm =  new promise(function(resolve,reject){
          resolve("1")
      })
      mm.then(function(res){ //then回调
          console.log(res)
      }).then(function(res){
          console.log(res)
      })

猜你喜欢

转载自www.cnblogs.com/xweizi/p/10089876.html
ES5
今日推荐