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?

desger131
  • 3
  • 3

1 Answers1

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.

RecencyEffect
  • 736
  • 7
  • 18