I'm having problem with anonymous functions node js, wanted to know how do I get the data off the async functions. This way it returns the empty web api, because it returns before the end of the async calls sqlite
restapi.get('/data', function(req, res){
var array = [];
db.each("SELECT value FROM counts", function(err, row){
array.push(row);
});
res.json(array);
});
Could someone explain me how it works and a way to solve? Thank you
That's the whole point of asynchronous programming with callbacks. An async function, instead of returning a result, accepts a callback, that will be triggered as soon as the job is done. The callback will receive the result of async work as its argument.
Don't expect async functions to return anything. Instead, nest your result handling logic in the callback you pass to that function.
Thus, your snipped should look something like this:
restapi.get('/data', function(req, res){
var array = [];
db.each("SELECT value FROM counts", function(err, row) {
if (row) {
array.push(row);
}
else {
res.json(array); // When there are no more rows
}
});
});
Working with plane callbacks is quite a pain. That endless nesting tend to clutter your code a lot. You can help yourself if you name your callbacks, and use the named versions instead of nesting. That will only get you so far. A better solution is using a control flow library like async. However, for that to work, all the callbacks must be composable -- that is, follow the convention of accepting the error object as the first argument. See this explaination, for example.