Friday 2 June 2017

Cant return contents from promise

Not getting how the below code is getting executed...

// readFile.js

const fs = require('fs');
var readFile = function readFile(fileName){
  return new Promise((resolve, reject)=>{
    fs.readFile(fileName, {encoding: 'utf-8'}, (err, contents)=>{
      if(err){
        reject(err);
      }
      resolve(contents);
    });
  });
};
module.exports.readFile = readFile;

//play.js
const {readFile} = require('./readFile');

var getText = function getTextFromFile(){

  readFile('readMe.txt').then((contents)=>{
     return contents;
  }).catch((err)=>{
    console.log(err);
  });
};
module.exports.getText = getText;

//someFile.js
const {getText} = require('./play.js');

var result = getText();
console.log(result);

When I execute someFile.js, it prints undefined. It should print the content as the then block in play.js file will only execute when the asynchronous task i.e., reading content from a file will end. Using above code, How can I return contents to some other file for example from play.js to someFile.js?



via Dinesh Choudhary

No comments:

Post a Comment