0

I am not sure how can I get the data callback/return from a function inside a function.

I would like to pass the processed data from processData function as callback and return this bufferData to be use as input other function. At the moment, the bufferData can't be returned from the processData function as it calls from traverse function. The code is below:

function processData(obj, key, value){
    var newobj=obj[key][0];
    obj[key].push(newobj);
    fs.readFile(__dirname + '/' + inFile, 'utf8', function(err, res) {
        if (err) return console.log(err);
          var data = JSON.parse(res);
          data.key=obj;
          bufferData=JSON.stringify(data);
          **callback(bufferData);** (not sure how to code it to return this bufferData)
}); }

function traverse(obj, func) {
  for (var key in obj) {
    func(obj, key, obj[key]);
    if (obj[key] !== null && typeof(obj[key])=="object") {
        traverse(obj[key], func);
    }       
} }

traverse(data, processData);
2
  • Its not really clear what you want to do with it. My initial question is what is callback(..) as he is not part of your code snippet. Can you please explain what you are trying to achieve. What you also should know is the rs.readFile Asynchronously reads the entire contents of a file therefore your traverse will continue execution and not wait for the readFile to complete. Commented Feb 24, 2017 at 2:15
  • Hi @Nico, I have added more information for this question, I would like to traverse a json file and process data in this file, then pass the new processed json to anther function. Commented Feb 24, 2017 at 2:24

1 Answer 1

1

It really makes no sense to return any data from callback.

You could just add a callback function to processData and then call it in callback of readFile.

Otherwise, you may use fs.readFileSync, with this you can get file data synchronously.

Sign up to request clarification or add additional context in comments.

1 Comment

I am new to javascript, could you please provide a code snippet?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.