我的代码位于我的文件中,如下所示:
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);
}
})
})
}
我从另一个文件调用上面的函数,如下所示:
objectRepositoryLoader.readObjectRepository(fileName)
.then(text => {
console.log(text);
})
.catch(error => {
console.log(error);
});
但它给我的错误是
.then(text => { ^
TypeError: Cannot read property 'then' of undefined
在这种情况下,如何使用promise调用另一个promise函数,然后在另一个promise函数中使用返回的值,并将计算值返回给调用函数,我可以在其中使用其他函数中的值。我听起来有点困惑。请帮忙
参考链接:Node.js : Call function using value from callback or async
以下是readObjectRepository定义:
readObjectRepository = function(fileName) {
var filePath = '../'+fileName;
xmlObjectRepositoryLoader(filePath)
}
答案 0 :(得分:3)
我在你的代码中遇到了这个问题。方法readObjectRepository
不返回承诺,并且实际上不返回任何内容
所以你不能链.then
要做到这一点 - 在readObjectRepository
的函数定义中返回xmlObjectRepositoryLoader
的承诺
进行此更改,它应该都很好
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
}