In a node.js application I need to do something like this: (pseudocode, of course)
if(loadedData is empty){
loadDatafromDatabase <<---- this one is async
}
useLoadedData
Of course, loading data from database is an async process, so useLoadedData tries to use data BEFORE the loading is complete. Is there any clean way to wait for loadDataFromDatabase to return its results, before going on?
I've seen many people mentioning callbacks as a correct solution, so I was tempted to do something like:
if(loadedData is empty){
loadDataFromDatabase( callback useLoadedData )
}else{
useLoadedData
}
but it looks quite dirty to me. Any better approach?
Thanks!
If you're ok with including node-fibers, you can try wait.for
https://github.com/luciotato/waitfor
var wait=require('wait.for');
function process(){
if(!data){
data = wait.for(loadDatafromDatabase);
// loadDatafromDatabase is *standard* async
// wait.for will pause the fiber until callback
}
useLoadedData(data);
}
wait.launchFiber(process);
The node way of doing this would be something like this:
db.query(queryString, callbackproc);
function callbackproc(resultSet) {
// do both cases here
}