es5如何实现promise_浅谈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的时候是包在一个函数中,在需要的时候去调用运行它:

functionAsync(){var test = new Promise(function(resolve,reject){

resolve("成功返回数据")

})returntest;

}

Async()

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

Async().then(function(res){

console.log(res)

//....

//可以对传过来的数据进行一系列操作

})

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

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

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

functionAsync1(){var p = new Promise(function(resolve, reject){

resolve('随便什么数据1');

});returnp;

}functionAsync2(){var p = new Promise(function(resolve, reject){

resolve('随便什么数据2');

});returnp;

}functionAsync3(){var p = new Promise(function(resolve, reject){

resolve('随便什么数据3');

});returnp;

}

Async1()

.then(function(data){

console.log(data);returnAsync2();

})

.then(function(data){

console.log(data);returnAsync3();

})

.then(function(data){

console.log(data);

});

//接下来可以清楚的看到:

//随便什么数据1

// 随便什么数据2

// 随便什么数据3

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

functionpromise (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:promiseif(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)

returnpromise

}var mm = new promise(function(resolve,reject){

resolve("1")

})

mm.then(function(res){ //then回调

console.log(res)

}).then(function(res){

console.log(res)

})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值