I am writing code for getting data.
First I call **getsomedata**
function to get data and inside getsomedata function I am calling another function getRandomdata to get data and returning it back to the previous function but it is returning undefined
. But in getRandomdata
data could be seen in console.log
.
Do I need to use callbacks
?
router.get('/get-data', function (req, res, next) {
var result = getsomedata(some_parameter);
console.log(result); // receiving undefined
res.send(result);
});
function getsomedata(some_parameter_recieved) {
var getsomedata = getRandomdata(random_params);
console.log(getsomedata); // receiving undefined
return getsomedata;
}
function getRandomdata(random_params_recieved) {
// after some calculation
console.log(random_data); // receiving proper data
return random_data;
}
Callback
- In JavaScript, higher order functions could be passed as parameters in functions. Since JavaSCript is a single threaded, only one operations happens at a time, each operation thats going to happen is queued in single thread. This way, passed functions(as parameter) could be executed when rest of the parent functions operation(async
) is completed and script can continue executing while waiting for results.Usually this
callback
function is passed in as the last argument in the function.Using
Callbacks
:Using
Promise
: