0

First time trying to use the Q promises library and I can't get my error callback to work:

   var fs = require('fs');
   var Q = require('q');

   var prom =  Q.nfcall(fs.writeFile('daa/write.txt', 'your mom', 'utf-8'));
   prom.then(function(err){
     console.log("error on writing file: ", err);
   });

I am deliberately giving a wrong destination to the write function to trigger an error. But on the command line I get this error:

fs: missing callback Error: ENOENT, open 'daa/write.txt'"

Why is my error callback not getting called? Why is my error callback missing?

Amit Erandole
  • 11,995
  • 23
  • 65
  • 103

2 Answers2

1

Turns out I needed to pass the function not call it. Both callbacks work as expected with this code:

var fs = require('fs');
var Q = require('q');

var prom =  Q.nfcall(fs.writeFile, 'data/write.txt', 'your mom', 'utf-8');
prom.then(function(){
  console.log('file written');
},function(err){
  console.log("error on writing file: ", err);
});
Amit Erandole
  • 11,995
  • 23
  • 65
  • 103
1

.nfcall accepts a function reference and not not the result of a function call.

var prom =  Q.nfcall(fs.writeFile, 'daa/write.txt', 'your mom', 'utf-8');

You should consider using Q.denodify if you intend to call fs more than once. Other libraries like Bluebird ship with a stronger promisifyAll function that converts an API to promises.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Could you tell me when I should be calling `done()` with promises? Does it apply to this example? – Amit Erandole Apr 25 '14 at 10:50
  • 1
    @AmitErandole if you use Bluebird you don't have to use `.done` anywhere since it will detect unhandled rejections itself. With Q you use it to indicate the end of a chain so unhandled rejections propagate. – Benjamin Gruenbaum Apr 25 '14 at 10:52
  • 1
    Yes please use bluebird before you get stuck with Q :P – Esailija Apr 25 '14 at 11:39
  • Has anyone found a bluebird equivalent for the convenience of `nfcall`? I don't want to have to `var promiseWrapped = promisify(myOldFunction)` and then `promiseWrapped(...).then(...)` because it feels like a waste/step backward after "upgrading" to bluebird... – JaKXz Jul 28 '15 at 17:40
  • @JaKXz `fromNode` (`fromCallback` in 3.0) - but don't use it, use promisify _once_ when you get the function initially, or better yet `promisifyAll` so it happens once per API automatically instead of constantly having to wrap things. – Benjamin Gruenbaum Jul 29 '15 at 06:04