Promise构造函数接受一个函数作为参数,函数里面有两个参数resolve和reject分别作为执行成功或者执行失败的函数。
通过then设置操作成功之后的操作,接受两个函数作为参数。
function _Promise() {
this.status = 'pending';
this.msg = '';
var cb = arguments[0];
var that = this;
cb(function() {
that.status = 'resolve';
that.msg = arguments[0];
}, function() {
that.status = 'reject';
that.msg = arguments[0];
});
return this;
}
_Promise.prototype.then = function() {
if (this.status == 'resolve') {
arguments[0](this.msg);
}
if (this.status == 'reject' && arguments[1]) {
arguments[1](this.msg);
}
}
//实例话
var promise = new _Promise(function(resolve, reject) {
resolve('success');
});
promise.then(function(data) {
console.log(data);
}, function(err) {
console.log(err);
});
网友评论