Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript嵌套函数返回_Javascript - Fatal编程技术网

Javascript嵌套函数返回

Javascript嵌套函数返回,javascript,Javascript,考虑到下面的代码块,如何让loadConfig返回JSON配置对象 function loadConfig(){ fs.readFile('./config.json', 'utf8', function (err, data){ if (err) throw err; var config = JSON.parse(data); }); return config; }; 返回的配置是未定义的,因为变量config不在loadConfig函数的作用域内,但是如果

考虑到下面的代码块,如何让loadConfig返回JSON配置对象

function loadConfig(){
  fs.readFile('./config.json', 'utf8', function (err, data){
    if (err) throw err;
    var config = JSON.parse(data); 
  });
  return config;
};
返回的配置是未定义的,因为变量config不在loadConfig函数的作用域内,但是如果return语句位于readFile匿名函数内,则它不属于loadConfig,似乎只会破坏嵌套的匿名函数

另一种解决方法是将匿名函数保存在一个变量中,然后由主函数loadConfig返回该变量,但没有成功

function loadConfig(){
  var config = fs.readFile('./config.json', 'utf8', function (err, data){
    if (err) throw err;
    var config = JSON.parse(data);
    return config;
  });
  return config;
};

问题依然存在;鉴于上述情况,如何让loadConfig返回config JSON对象

简单的答案是你不能

这些是异步调用,这意味着您的return语句不会等待响应,它将继续执行。因此,当您调用函数时,将首先触发return语句,然后接收响应


相反,对您的操作使用成功回调函数,而不是返回值。

您也可以使用同步版本的readFile或是,Promise是另一种解决方案。
这里的文档:

只需定义/使用承诺:

function loadConfig(){
  return new Promise(function(resolve, reject) {
    fs.readFile('./config.json', 'utf8', function (err, data){
      if (err) reject(err);

      var config = JSON.parse(data);
      resolve(config); 
    });
  })
};
使用它:

loadConfig().then(function(config) {
  // do something with the config
}).catch(function(err){
  // do something with the error
});
使用readFileSync而不是readFile。因为readFile是一种异步方法

function loadConfig(){
  var fileContent = fs.readFile('./config.json', 'utf8').toString();
  return fileContent?JSON.parse(fileContent):null;
};

readFile是异步的-因此您永远无法从该函数返回。阅读关于promisesPromises的文章是您的朋友!不建议重复使用sync调用,这将挂断浏览器并使页面无响应。这是一个阻塞调用,也是一个糟糕的主意,始终异步这是最好的方法,或者使用successs,因此我不能只使用全局变量和配置对象,我可以随时引用它;我需要使用configVar。然后。。。;要访问config对象,我认为不能将输入返回给then函数。我说的对吗?您可以有一个全局变量,但由于操作是异步的,您不知道该变量何时被填充。使用then可以避免这种情况,因为一旦设置了配置,就可以在下一个函数中使用它。这在其他语言中称为承诺或未来,是处理异步操作的惯用方法。你基本上是返回一个函数,你可以在它有结果后立即使用它。请在此阅读更多内容