Abhinav Abhinav - 1 year ago 89
Node.js Question

nodejs how to use promise output in other file and modify it and then return its value

I have code in one of my file like below:

this.xmlObjectRepositoryLoader = function (xmlPath){
var innerMap = {};
var elementName;
var filePath = xmlPath+'.xml'
var self = this
return new Promise(
function(resolve, reject){
console.log("In xmlObjectRepositoryLoader : "+filePath)
.then(text => {
var doc = domparser.parseFromString(text,"text/xml");
var elements = doc.getElementsByTagName("Element");
for(var i =0 ; i< elements.length;i++){
var elm = elements[i];
elementName = elm.getAttribute("name");
var params = elm.getElementsByTagName("param");
innerMap = {};
for(var j =0 ; j< params.length;j++){
var param = params[j];
var locatorType = param.getAttribute("type");
var locatorValue = param.getAttribute("value");
innerMap[locatorType] = locatorValue;
map[elementName] = innerMap;
console.log(map) // prints the map
.catch(error => {

this.readFilePromisified = function(filename) {
console.log("In readFilePromisified : "+filename)
return new Promise(
function (resolve, reject) {
fs.readFile(filename, { encoding: 'utf8' },
(error, data) => {
if (error) {
} else {

I am calling above function from another file as below:

.then(text => {
.catch(error => {

But it gives me error as

.then(text => { ^

TypeError: Cannot read property 'then' of undefined

In this case how can I use promise to call another promise function and then use the returned value in one more promise function and return calculated value to calling function where I can use the value in other functions. I sound a bit confused. Please help

Referrence link: Node.js : Call function using value from callback or async

Following is readObjectRepository definition :

readObjectRepository = function(fileName) {
var filePath = '../'+fileName;

Answer Source

I got the issue in your code. The method readObjectRepository doesn't return a promise and infact doesn't return anything

So you cannot chain .then

To do that- in the function definition of readObjectRepository return the promise of xmlObjectRepositoryLoader

Make this change and it should be all good

readObjectRepository = function(fileName) {
        var filePath = '../'+fileName;
        return xmlObjectRepositoryLoader(filePath)   //This will return the promise of xmlObjectRepositoryLoader which you can handle in 'then' and obtain the text
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download