Reputation: 2243
I've a function, which returns a promise, inside that I call another function, and the status of this promise is based on the status of the inner promise.
Is there a way to shorthand this process. Look at the example below.
function foo(bar) {
var deferred = Q.defer();
switch (bar) {
case 'baz1':
deferred.resolve();
break;
case 'baz2':
deferred.reject();
break;
case 'this_is_how_i_do_it':
funReturningPromise().then(function (value) {
deferred.resolve(value);
}, function (err) {
deferred.reject(err);
});
break;
case 'can_we_do_it_like_this':
// can we do something like this, which will resolve or reject the deferred,
// based on the status promise returned by funReturningPromise().
// 'chain' is just a name
funReturningPromise().chain(deferred);
break;
}
return deferred;
}
Thanks,
Upvotes: 0
Views: 3707
Reputation: 728
If you already have the deferred, then you can resolve it with another promise.
deferred.resolve(funReturningPromise())
Otherwise, what Kris said.
Upvotes: 0
Reputation: 3846
If you return a value, throw an exception, or return a promise from inside any function managed by Q, particularly the callbacks given to then
, the chained promise will “become” that value, exception, or promise.
var foo = Q.fbind(function (bar) {
switch (bar) {
case 'baz1':
return;
case 'baz2':
throw new Error("");
case 'this_is_how_you_can_do_it':
return funReturningPromise();
}
});
In this case, I’m using Q.fbind
to guarantee that the return result is a promise, but if foo
were called in the context of a promise handler, just like funReturningPromise
, the fbind
would be unnecessary. If you want to invoke a function immediately and get a promise for the result, you can also use fcall
.
Upvotes: 1
Reputation: 3160
It doesn't work as well for more complex functions, but in your example you could do something like:
case 'can_we_do_it_like_this':
return funReturningPromise();
You can also try adding your own promise.prototype.chain
method if you're using only q promises.
Upvotes: 2