Understanding Async in node js using promises

108 Views Asked by At

I am trying to understand the following problem:

var fs = require('fs');
var Promise = require('bluebird');

Promise.promisifyAll(fs);

fs.readFileAsync('read.js','utf8').then(function(content) {
  console.log(content);
}).catch(function(error) {
  console.log(error);
});

I understood that since I am promisifying fs library I can use readFileAsync as promise. But if i change the name of readFileAsync to readFileAs I am getting the following error:

C:\Users\nniranja\Venkat\promises_github.js:17
fs.readFileA("read.js",'utf8').then(function(content)
   ^
TypeError: undefined is not a function
    at Object.<anonymous> (C:\Users\nniranja\Venkat\promises_github.js:17:4)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

Please help me to understand the significance of Async. Thank you.

4

There are 4 best solutions below

0
On

readFileAs is not a function in the fs module, nor is it a property that bluebird would add to the module. So, it is expected that there is no readFileAs function found.

0
On

According to the documentation, readFileAs ain't a supported function so it ain't an asynchronous issue.

0
On

Normal node calls come in pairs like

  • readFile
  • readFileSync

The Bluebird library defines functions such as readFileAsync when you promisify a library, so those are the ones you want to call.

@AndrewEisenberg is correct, and it looks like your keyboard is keeping letters from appearing as you have readFileAsync, readFileAs, and readFileA in your question.

Pay close attention to what you're typing in coding - every character counts!

2
On

The method readFileAs you are trying to use doesn't exist on the fs library that's why you see that error.

The only ones that exist for purposes of reading files are:

  • read
  • readSync
  • readFile
  • readFileSync

According to bluebird documentation, after you call Promise.promisifyAll(fs); you may use fs's methods exactly as they are documented, except by appending the Async-suffix to method calls and using the promise interface instead of the callback interface.

So following the API documentation you only append the Async-suffix to methods that exists on the fs library like the ones listed above.