【发布时间】:2018-05-09 17:29:32
【问题描述】:
我有一个函数 getHighScores,我想将它放入一个 JSON 文件并获取给定 game 的分数对象,对它们进行排序,然后返回其中的顶部 amount。
这是我的(损坏的)代码:
function getHighScores(game, amount) {
var highScores = null;
fs.readFile('scores.json', 'utf8', function (error, data) {
var scoresObj = JSON.parse(data);
var gameScores = scoresObj.games[game];
sortedScores = gameScores.sort(compareScoreObjects);
highScores = sortedScores.slice(0, amount);
});
return highScores;
}
console.log(getHighScores('snake', 10));
这是记录null,因为在fs.readFile 的回调函数范围内无法访问highScores。
有什么方法可以在保持代码逻辑的同时做到这一点 - 我可以简单地让 getHighScores 返回数据?如果不是,我应该如何考虑这个问题?
【问题讨论】:
标签: javascript json node.js callback