Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

javascript - Chaining promises without using 'then'

I have an object (foo) that exposes several methods as promises (using jQuery deferred). The way I did it ended up with this kind of code:

var foo = createNewFoo();
$.when(foo.method1(arg))
    .then(foo.method2)
    .then(foo.method3);

I wish to refactor the below code to be nicer and look like this:

var foo = createNewFoo()
    .method1(arg)
    .method2()
    .method3();

But I'm not sure how to implement foo that it would be possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes sure, you just need to extend your Deferreds to have these methods:

function MyRpc { // if you can use ES2015 - this should be a `class`
  this._deferred = new $.Deferred();
}
// teach it to be a promise
MyRpc.prototype.then = function(onFulfilled, onRejected) {
  return this._deferred.then(onFulfilled, onRejected);
};

// teach it to be a deferred
MyRpc.protototype.resolve = function(arg) {
  this._deferred.resolve(arg);
};

MyRpc.prototype.reject = function(arg) {
  this._deferred.reject(arg);
};

// define your methods!

MyRpc.prototype.method1 = function(arg) {
  var p = this._deferred.then(function(value) {
    // logic of `method1` from foo.method1 here
  });
  var rpc = new MyRpc(); // our continuation;
  p.then(function(v) { rpc.resolve(v) }, function(e) { rpc.reject(e); });
  return rpc;
};

Of course, with a real promise library all this is a lot easier than with jQuery's minimal promises.

This would let you do:

var rpc = new MyRpc();
rpc.method1(1).method1(2).method1(3); // can also `.then` here

I'm not sure it's worth it, but it works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...