我的节点js程序在读取json文件时给我一个"TypeError:无法读取未定义的属性'then'" [英] My node js program is giving me a "TypeError: Cannot read property 'then' of undefined", when reading a json file
本文介绍了我的节点js程序在读取json文件时给我一个"TypeError:无法读取未定义的属性'then'"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过程序读取frpm的json文件文件夹,并且我想使用GET列表端点来浏览浏览器或邮递员,但是我遇到了上述TypeError.这是我的代码:
I'm trying to read frpm a json file folder withing my program and i want to use a GET list endpoint to read through browser or postman, but i'm getting the above TypeError. Here is my code:
model.js:
const fs = require('fs');
function loadTeams() {
return new Promise((resolve, reject) => {
fs.readFile('./json/prov-nodes.json', (err, data) => {
if (err) reject(err);
const teams = JSON.parse(data);
console.log(teams);
resolve(teams);
});
});
}
app.use(bodyParser.json());
app.use(bodyParser.json());
app.get('/list', (req, res) => {
let teams = [];
loadTeams()
.then(function(data){
teams = JSON.stringify(data);
console.log(teams);
**res.send(teams);** //intended to send to browser/postman response
console.log('try...part ..read call');
})
.catch(error => console.log(error))
res.send("My root page");
console.log(teams);
});
推荐答案
loadTeams
函数不会返回promise,因此您无法调用 .then()
.
The loadTeams
function does not return a promise, and therefore you cannot call .then()
.
您可以将函数包装在一个这样的Promise中:
You can wrap the function in a promise like this:
function loadTeams() {
return new Promise(function(resolve, reject) {
fs.readFile('./json/prov-nodes.json', (err, data) => {
if (err) reject(err);
try {
const teams = JSON.parse(data);
return resolve(teams);
} catch(e) {
reject(e);
}
});
});
}
这篇关于我的节点js程序在读取json文件时给我一个"TypeError:无法读取未定义的属性'then'"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文