若是須要獲取一個函數中異步操做的結果,則必須經過回調函數來獲取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} ] }