1
function readTextFile(filename, callback){
    var fs = require('fs');
    fs.readFile(filename, 'utf8', function(err, data){
        if(err){
            throw err;
        }else{
            callback(data);
        }
    });
}

var set1 = [];
var set2 = [];
var set3 = [];
var set4 = [];
var set5 = [];

readTextFile("./data/names.json", function(text){
    var names = JSON.parse(text);
    set1 = names.prop1.prop2;
    set2 = names.prop1.prop3;
    set3 = names.prop1.prop4;
    set4 = names.prop5.prop2;
    set5 = names.prop5.prop3;
});
console.log(set1);

Running this section of code, using "node jsonRead.js" returns [ ] for any array called in console.log(). This section of code used to work about 80% of the time, but now it doesn't work at all, and I'm not sure why. I would appreciate any advice on how to get it working again.

4

2 Answers 2

1

maybe the read process is still going on.

try the console.log(set1); in the callback:

readTextFile("./data/names.json", function(text){
    var names = JSON.parse(text);
    set1 = names.prop1.prop2;
    set2 = names.prop1.prop3;
    set3 = names.prop1.prop4;
    set4 = names.prop5.prop2;
    set5 = names.prop5.prop3;

    console.log(set1);
});

This is cause the callbackfunction of readTextFile is executed when reading finished, whereas the other code is executed as written.

You could solve this by using Promises. Checkout the q library for example: https://github.com/kriskowal/q

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

Comments

1

Node.js paradigm of executing code is Asynchronous , means it will execute next line of code after calling async method . In your above example readTextFile is called and execution will continue to next line . It will not wait for return .

1 Comment

How can I make the function return the data I need exactly when I need it, while still keeping it asynchronous?

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.