Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js Q promises library - how to call back from ninvoke with a proper argument list

Tags:

node.js

promise

q

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.
});
like image 565
Nathan Ridley Avatar asked Dec 06 '25 08:12

Nathan Ridley


1 Answers

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.

like image 121
ForbesLindesay Avatar answered Dec 08 '25 22:12

ForbesLindesay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!