Question

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?

Was it helpful?

Solution

.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.

OTHER TIPS

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);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top