Abhinav Abhinav - 2 months ago 10
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)
self.readFilePromisified(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;
innerMap={};
}
console.log(map) // prints the map
resolve(text)
})
.catch(error => {
reject(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) {
reject(error);
} else {
resolve(data);
}
})
})
}


I am calling above function from another file as below:

objectRepositoryLoader.readObjectRepository(fileName)
.then(text => {
console.log(text);
})
.catch(error => {
console.log(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;
xmlObjectRepositoryLoader(filePath)
}

Answer

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
    }
Comments