0

I'm learning node.js and I have a problem. How to get data from function to variable?

function loadOrInitializeTaskArray(file, cb) {
        fs.exists(file, function(exists) {
                var tasks = [];
                if (exists) {
                    fs.readFile(file, 'utf8', function(err, data) {
                            if (err) throw err;
                            var data = data.toString();
                            var tasks = JSON.parse(data || '[]');
                            cb(tasks);
                    })
                } else {
                        cb([]);
                }
        })
}



function listTasks(file) {
        loadOrInitializeTaskArray(file, function(tasks) {
                for (var i in tasks) {
                        console.log(tasks[i]);
                }
        })
}

Function listTasks works correctly, but I would like create own function, for example customListTasks:

function customListTasks(file) {
        var list = loadOrInitializeTaskArray(file, function(){});
        console.log(list);
}

This not return me errors, but console.log on list return me "undefined". How can I get this data to variable list?

3
  • use Bluebird coroutine function and using that you can yield promises Commented Apr 8, 2017 at 10:19
  • stackoverflow.com/questions/5010288/… Commented Apr 8, 2017 at 10:32
  • You cannot expect to get an asynchronous result synchronously. You'll have to get it asynchronously (callback, promise). Commented Apr 8, 2017 at 10:40

1 Answer 1

0

Short answer: you can not.

Because the loading in loadOrInitializeTaskArray is asynchronous, all the magic has to happen in the callback that you are passing. You cannot just 'return' a value from it.

Option 1: Place all logic that depends on the loaded data in the anonymous function that you pass as callback.

var list = loadOrInitializeTaskArray(file, function(tasks){
    console.log(tasks);
});

Option 2: Use Promises. They work essentially like callbacks, but are slightly more flexible and make chaining easier.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.