es6中Promise对象,代表一个异步操作,其不受外界影响,有三种状态
* Pending(进行中、未完成的)
Resolved(已完成,又称 Fulfilled)
Rejected(已失败)
优势1、解决回调地狱(Callback Hell)问题2、更好地进行错误捕获
*
* Promise.then(成功回调).catch(错误或失败回调)
* Promise.all([func1(),func2()]).then((返回值)=>{console.log()返回值是个数组["函数1返回值","函数2返回值"]})所有异步操作执行完后才执行回调。
那么在es5用如何实现promise呢?
请看下方
//1、使用function创建一个MyPromise方法即构造函数 带一个参数即回调函数fn
function MyPromise(fn) {
this.value;
this.status = 'pending';
this.resolveFunc = function() {};
this.rejectFunc = function() {};
fn(this.resolve.bind(this), this.reject.bind(this));
}
//2 、给MyPromise添加一个原型方法resolve,将val值传进去,利用
MyPromise.prototype.resolve = function(val) {
var self = this;
if (this.status == 'pending') {
this.status = 'resolved';
this.value = val;
setTimeout(function() {
self.resolveFunc(self.value);
}, 0);
}
}
//3 、给MyPromise添加一个原型方法reject,将val值传进去,利用
MyPromise.prototype.reject = function(val) {
var self = this;
if (this.status == 'pending') {
this.status = 'rejected';
this.value = val;
setTimeout(function() {
self.rejectFunc(self.value);
}, 0);
}
}
MyPromise.prototype.then = function(resolveFunc, rejectFunc) {
var self = this;
return new MyPromise(function(resolve_next, reject_next) {
function resolveFuncWrap() {
var result = resolveFunc(self.value);
if (result && typeof result.then === 'function') {
//如果result是MyPromise对象,则通过then将resolve_next和reject_next传给它
result.then(resolve_next, reject_next);
} else {
//如果result是其他对象,则作为参数传给resolve_next
resolve_next(result);
}
}
function rejectFuncWrap() {
var result = rejectFunc(self.value);
if (result && typeof result.then === 'function') {
//如果result是MyPromise对象,则通过then将resolve_next和reject_next传给它
result.then(resolve_next, reject_next);
} else {
//如果result是其他对象,则作为参数传给resolve_next
resolve_next(result);
}
}
self.resolveFunc = resolveFuncWrap;
self.rejectFunc = rejectFuncWrap;
})
}
**如有不解,请加群 897149839**