Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 967
Kai Avatar asked Aug 19 '14 17:08

Kai


2 Answers

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.

like image 53
Oleksandr.Bezhan Avatar answered Sep 28 '22 13:09

Oleksandr.Bezhan


The accepted answer is good but to address the difference:

  • nfapply expects an array of arguments
  • nfcall expects arguments provided individually

For Example:

Q.nfcall(FS.readFile, "foo.txt", "utf-8");
Q.nfapply(FS.readFile, ["foo.txt", "utf-8"]);

See https://github.com/kriskowal/q/wiki/API-Reference#qnfapplynodefunc-args

like image 29
kampsj Avatar answered Sep 28 '22 15:09

kampsj