Node.js Q promises library - how to call back from ninvoke with appropriate argument list
q.ninvoke(myNodeJsFunc).then(function(result) {
console.log(arguments);
});
function myNodeJsFunc(callback) {
callback(null, arg1, arg2, ..., argN); // first argument is null as no error occurred
}
If I go back arg1
, it result
will arg1
. If I pass multiple arguments, it result
will be an array of arguments. Is there a way to return a Q call with each of my arguments being applied to the function as separate arguments, instead of being bound to an array and passed back as one argument? I was hoping I could use named arguments instead of sifting through an array of arbitrary elements.
In fact, I would like to be able to do this:
q.ninvoke(myNodeJsFunc).then(function(arg1, arg2, arg3) {
// do stuff
if(arg2) {
// do stuff
}
// etc.
});
source to share
You can, what you need is called spread
:
q.ninvoke(myNodeJsFunc)
.spread(function(arg1, arg2, arg3) {
// do stuff
if(arg2) {
// do stuff
}
// etc.
});
The reason this is not the default is because part of the premise of promises is to make them as similar as possible to their synchronous counterparts. Thus, in the future you will be able to:
spawn(function* () {
var res = yield q.ninvoke(myNodeJsFunc);
res[0], res[1]...
});
Which looks synchronized except for the keyword yield
where the magic happens.
The operator is spread
correct, because in the next version of JavaScript you will be able to write:
spawn(function* () {
let [arg1, arg2, arg3...] = yield q.ninvoke(myNodeJsFunc);
arg1, arg2 ...
});
which is nicely parallel to synchronous codde:
let [arg1, arg2, arg3...] = mySyncFunc();
arg1, arg2 ...
In short, if you want multiple arguments, replace then
with spread
.
source to share