我想为jQuery的Deferred对象创建一个包装,以扩展其方法:“ resolve”和“ reject”,更重要的是其promise的“ then”和“ fail”方法。但是,我不想使用“ fail”方法,而是要用“ catch”方法替换/重命名它,而要用“ thenNew”代替它的“ then”方法。
到目前为止,我一直在努力做到这一点:
function ObjectPromise () {
this.instance = $.Deferred();
this._promise = this.instance.promise;
}
工作方法:
ObjectPromise.prototype.resolve = function ( data ) {
this.instance.resolve(data);
}
ObjectPromise.prototype.reject = function ( data ) {
this.instance.reject(data);
}
不起作用的方法(“ catch”和“ thenNew”):
ObjectPromise.prototype.promise = function () {
this.prom = this._promise()
this.prom.thenNew = this.prom.then;
this.prom.catch = this.prom.fail;
return this.prom;
}
这样,当我具有以下功能时:
function getUsersFromDb () {
var deferred = new ObjectPromise();
setTimeout( function () {
deferred.resolve( 'data_resolved' );
}, 2000 );
return deferred.promise();
}
然后执行它,我想要以下链:
getUsersFromDb().thenNew( function () { .... })
.thenNew( function () {
var deferred = new ObjectPromise();
setTimeout( function () {
deferred.reject( 'data_rejected' );
}, 2000 );
return deferred.promise();
} ).thenNew()...
.catch( function ( error ) {
....
} );
谢谢!