如果需要获取一个函数中异步操作的结果,则必须通过回调函数来获取
简单例子:
function fun(callback) {
setTimeout(function () {
var data = 1;
callback(data);
})
}
fun(function (data) {
console.log(data);
})
封装 API students.js
exports.find = function (callback) {
fs.readFile('./db.json', function (err, data) {
if (err) {
return callback(err);
}
callback(null, JSON.parse(data).students);
});
};
使用:
var students = require('./students')
router.get('/students', function(req, res) {
students.find(function (err, data) {
res.render('index.html', data)
})
})
db.json 数据
{
"students" :[
{"id": 1, "name": "小白", "xuehao": 201561361351, "gender": 1, "core": 88},
{"id": 2, "name": "小黑", "xuehao": 201561361352, "gender": 0, "core": 85},
{"id": 3, "name": "小绿", "xuehao": 201561361353, "gender": 0, "core": 88},
{"id": 4, "name": "小红", "xuehao": 201561361354, "gender": 1, "core": 95}
]
}
exports.find = function (callback) {
fs.readFile('./db.json', function (err, data) {
if (err) {
return callback(err);
}
callback(null, JSON.parse(data).students);
});
};