我有 Node 项目。
根文件是 index.js
和文件 helper.js
,这里我有一些辅助函数并将其导入到 index.js
。
我尝试使用 helper.js
中的函数获取一些数据,但是当我在 index.js
中调用它时,它返回 undefined
。
但在 helper.js
中一切正常,console.log
显示我需要的数据。
我该如何解决这个问题?
index.js 文件内容:
const helper = require('./helper');
let data = helper.getData();
console.log(data); // undefined
helper.js 文件内容:
const fs = require('fs');
module.exports = {
getData: () => {
fs.readFile('data.json', 'utf8', (err, data) => {
const allData = JSON.parse(data);
console.log(allData); // IS OK!
return allData;
});
}
}
最佳答案
您可以使用 Promise :
const fs = require('fs');
module.exports = {
getData: () => {
return new Promise(function(resolve, reject){
fs.readFile('data.json', 'utf8', (err, data) => {
if(err){
reject(err);
} else {
try {
resolve(JSON.parse(data));
} catch(ex){
reject(ex);
}
}
});
});
}
}
然后:
helper.getData().then(function(data){
console.log(data);
}, function(err){
// here something failed
});
问题是 fs.readFile
方法是异步的,结果不会给你任何数据 check the documentation here .
所以一个选择是使用 Promise正如我所做的那样,或者按照@Tatsuyuki Ishi 的回答中的建议使用callback
,您可以查看有关callback
实现的文档。
关于javascript - 返回值时未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43517272/