若是须要获取一个函数中异步操做的结果,则必须经过回调函数来获取html
简单例子:json
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 数据ui
{ "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} ] }