lux
lux

Reputation: 411

Javascript nested functions return

With consideration of the following code-block, how would one go about having loadConfig() return the JSON config object?

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

The returned config is undefined as the variable config is outside the scope of the loadConfig() function, yet if the the return statement is located inside the readFile anonymous function, it doesn't fall through to loadConfig(), and seemingly only breaks the nested anonymous function.

Another attempt has been made to resolve this by saving the anonymous function in a variable which is then returned by the main function loadConfig, but to no avail.

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

The question stands; given situation sketched above, how would one make loadConfig() return the config JSON object?

Upvotes: 0

Views: 3273

Answers (4)

ajai Jothi
ajai Jothi

Reputation: 2294

Use readFileSync instead of readFile. Since readFile is an async mthod.

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

Upvotes: 0

caisah
caisah

Reputation: 2087

Just define/use a 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); 
    });
  })
};

and to use it:

loadConfig().then(function(config) {
  // do something with the config
}).catch(function(err){
  // do something with the error
});

Upvotes: 3

Tom
Tom

Reputation: 13

You can also use the synchronous version of readFile or yes, Promise is the other solution. Doc here: https://nodejs.org/api/fs.html#fs_fs_readfilesync_file_options

Upvotes: -2

Abhinav
Abhinav

Reputation: 1200

Simple answer is you can't.

These are async call, which mean your return statement will not wait for your response, it will continue to execute. Hence when you call function your return statement is fired first and then you receive the response.

Instead, use success callback function for your operation and not return value..

Upvotes: 0

Related Questions