简体   繁体   English

如何从回调函数获取值到外部作用域?

[英]How do I get a value from a callback function to the outside scope?

I have a function getHighScores which I want to go into a JSON file and get score objects for a given game , sort them, and return the top amount of them. 我有一个函数getHighScores ,我想进入一个JSON文件并获取给定game得分对象,对其进行排序,然后返回它们的最高amount

This is my (broken) code: 这是我的代码(断开):

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));

This is logging null , because highScores cannot be accessed within the scope of the callback function for fs.readFile . 这将记录为null ,因为无法在highScores的回调函数的范围内访问fs.readFile

Is there any way to do this while maintaining the logic of my code - where I can simply have getHighScores return the data? 有什么方法可以在保持代码逻辑的同时进行操作-在这里我可以简单地让getHighScores返回数据? If not, how should I be thinking about this problem? 如果没有,我应该如何考虑这个问题?

The problem here is you're using readFile, which is an asynchronous method. 这里的问题是您正在使用readFile,这是一个异步方法。 Meaning by the time this method resolves, highScores is already returned. 意味着到该方法解析时,highScores已经返回。

Checkout the readFileSync method ( https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options ) which is a synchronous version of readFile. 检出readFileSync方法( https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options ),该方法是readFile的同步版本。

You can then change your code as follows. 然后,您可以按以下方式更改代码。

function getHighScores(game, amount) {
  var scoresObj = fs.readFileSync('scores.json', 'utf8');
  var parsedScoresObj = JSON.parse(data);
  var gameScores = parsedScoresObj.games[game];
  var sortedScores = gameScores.sort(compareScoreObjects);
  var highScores = sortedScores.slice(0, amount);
  return highScores;
}

From what I have read, fs.readfile is async. 根据我的阅读,fs.readfile是异步的。 So highScores is returning immediately instead of wating to read the file. 因此highScores立即返回,而不是等待读取文件。 You could change the code to be synchronous. 您可以将代码更改为同步。

function getHighScores(game, amount) {
var highScores = null;
var data = fs.readFileSync('scores.json', 'utf8')
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));

If you want to keep it asynchronous though then you should check this link 如果您想使其保持异步,则应检查此链接

How do I return the response from an asynchronous call? 如何从异步调用返回响应?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM