What's difference between Q.nfcall and Q.fcall?

Kai picture Kai · Aug 19, 2014 · Viewed 9.1k times · Source

I am new to node.js. I am trying to understand Q.nfcall. I have the following Node.js code.

function mytest() {
  console.log('In mytest');
  return 'aaa';
}

Q.nfcall(mytest)
.then(
  function(value){
    console.log(value);
});

My expected output should be:

In mytest 
aaa

But the actual output is:

In mytest

After I changed Q.nfcall to Q.fcall in the code above, the output became what I expected:

In mytest 
aaa

Why's that? What's difference between Q.nfcall and Q.fcall? Thanks.

Answer

Oleksandr.Bezhan picture Oleksandr.Bezhan · Aug 19, 2014

From the Q documentation:

If you're working with functions that make use of the Node.js callback pattern, where callbacks are in the form of function(err, result), Q provides a few useful utility functions for converting between them. The most straightforward are probably Q.nfcall and Q.nfapply

What it means is that nfcall() expects Node-style function(cb) which calls cb(error, result). So when you write:

Q.nfcall(mytest)
.then(
  function(value){
    console.log(value);
});

Q expects that mytest calls passed callback with (error, value) and Q then calls your next callback with value. So your code should look something like this(here is Plunkr):

function mytest(cb) {
  console.log('In mytest');
  cb(null, 'aaa');
}

Q.nfcall(mytest)
.then(
  function(value){
    console.log('value', value);
});

You can look into nfcall() test cases to go deeper how it should be used.