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 only pass back arg1, result will be arg1. If I pass back multiple arguments, result will be an array of arguments. Is there a way to have Q call back with each of my arguments applied to the function as individual arguments, rather than being bundled into an array and passed back as a single argument? I was hoping to be able to use named arguments rather than having to sift through an array of arbitrary elements.
Effectively, I would like to be able to do this:
q.ninvoke(myNodeJsFunc).then(function(arg1, arg2, arg3) {
// do stuff
if(arg2) {
// do stuff
}
// etc.
});
You can, what you're after is called spread:
q.ninvoke(myNodeJsFunc)
.spread(function(arg1, arg2, arg3) {
// do stuff
if(arg2) {
// do stuff
}
// etc.
});
The reason this isn't the default is that part of the premise behind promises is to make them as much like the synchronous counterparts as possible. That way in the future you'll be able to do:
spawn(function* () {
var res = yield q.ninvoke(myNodeJsFunc);
res[0], res[1]...
});
Which looks synchronous, except for the yield keyword which is where the magic happens.
The spread operator is fine because in the next version of JavaScript you would be able to write:
spawn(function* () {
let [arg1, arg2, arg3...] = yield q.ninvoke(myNodeJsFunc);
arg1, arg2 ...
});
which nicely parallels the synchronous codde:
let [arg1, arg2, arg3...] = mySyncFunc();
arg1, arg2 ...
In short, when you want multiple arguments, replace then with spread.