I'm using Q together with RequireJS. Oftentimes I find myself writing code like this:
function someFunc() {
// prepare result
var res = Q.defer();
require( ['someOtherModule'], function( mod ) {
// do some stuff with mod
mod().then( function(){
// ...
return somePromise;
})
.then( function( val ) {
// resolve the functions deferred
res.resolve( val );
}, function( err ){
// relay error
res.reject( err );
});
});
// return promise
return res.promise;
}
So i have a function someFunc()
, which requests a module (it may determine at runtime, which module to load) and then does some stuff with that module possibly using a promise chain itself (in the example just one element in the chain, but can be more).
In the end I just want to relay the results of my inner promise chain to the outer deferred/promise.
I know I could resolve with the promise itself like this
res.resolve(
mod().then( function(){
// ...
return somePromise;
})
);
But when the chain gets longer or includes more code, this will be hardly readable.
I'm basically looking for a method/way to do something like this:
mod().then( function(){
// ...
return somePromise;
})
.relay( res );
Which would be equivalent to the above code wrt to maintaining errors within the promise chain.
I already looked into Q.nfcall()
or Q.nfapply()
, but those only work for callbacks, which have to parameters error
and result
. In the case of a require()
call, however, the parameters are the requested module, which does not comply with the signature Q wants to have ...