Let's first rewrite your pseudo-code to reflect the async nature of the logic contained within the first function:
foo(a1,a2,a3){
//do some *async* logic here
regressionFunction(a1, a2, a3, function(result) {
data = result;
});
return data;
//lets say the data = 15
}
foo2(){
//do some stuff
data = foo(a1,a2,a3)
console.log(data)
}
This will result in data being undefined in foo2 because data has not yet been set when foo returns. Hence, async.
There are several ways to deal with this, but the simplest at this point is probably to use a Promise. Think of a Promise as a placeholder for a guaranteed future value, which we can then instruct our code to wait upon before proceeding.
Instead of simply returning data in foo, return a Promise to resolve when data is ready:
foo = function(a1,a2,a3) {
return new Promise(function(resolve, reject) {
regressionFunction(a1, a2, a3, function(result) {
resolve(result);
});
});
}
And then instead of expecting the result of foo to be immediately available in foo2, we use the Promise instance's then method.
foo2 = function() {
//do some stuff
var data2 = foo(5,5,5);
data2.then(function(result) {
console.log('Finally got a result!', result);
});
}
If you need to return a value from foo2 dependent upon the result of foo, of course, you would need to return a Promise there as well. Conveniently, the the return type of a .then method is itself a Promise so we can simply return it:
foo2 = function() {
//do some stuff
var data2 = foo(5,5,5);
return data2.then(function(result) {
console.log('Any function receiving this as input can access the result now by accessing the `.then` method of this function');
return result;
});
}
This is a simplification of Promises, but should get you started.