function NewPromise(fn){ this.state = 'PENDING' this.fulfillList = [] this.rejectList = [] fn(this.resolve.bind(this),this.reject.bind(this)) } //成功,执行成功队列的函数 NewPromise.prototype.resolve = function(data){ this.state = 'FULFILLED' var args = [].slice.call(arguments) setTimeout(function () { this.fulfillList.forEach(function (itemFn,key,arr) { itemFn.apply(null,args) arr.shift() }) }.bind(this),0) } //失败,执行失败队列的函数 NewPromise.prototype.reject = function(data){ this.state = 'REJECTED' var args2 = [].slice.call(arguments) setTimeout(function () { this.rejectList.forEach(function (itemFn,key,arr) { itemFn.apply(null,args2) arr.shift() }) }.bind(this),0) } //成功回调函数 NewPromise.prototype.done = function(handle){ if(typeof handle === 'function') this.fulfillList.push(handle) else throw new Error('回调函数出错') return this } //失败回调函数 NewPromise.prototype.fail = function(handle){ if(typeof handle === 'function') this.rejectList.push(handle) else throw new Error('回调函数出错') return this } //失败成功写在一个方法内 NewPromise.prototype.then = function(fulfill,reject){ this.done(fulfill)||function () {} .fail(reject)||function () {} return this } //失败成功都执行一个函数 NewPromise.prototype.always = function(handle){ this.done(handle)||function () {} .fail(handle)||function () {} return this } var prm = new NewPromise(function (resolve,reject) { setTimeout(function(){ resolve('成功的参数') reject('失败的参数') },1000) }) prm.then(function(data){ console.log(data) }).fail(function(data){ console.log(data) })