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.
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.
The accepted answer is good but to address the difference:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With