1

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!

3
  • 2
    Seems fine to me. Just define useLoadedData() once elsewhere and call it/pass it as a callback in your code as many times as you want Commented Aug 25, 2014 at 18:42
  • 1
    That only looks "dirty" if you're not used to looking at async/callback code. It's the async version of if(loadedData is empty) {loadData; useData;} else{useData;} Commented Aug 25, 2014 at 18:51
  • I'm not very used to writing async code :) I guess tweaking the program flow to adapt to situations like this one is not considered bad practice. Thanks Commented Aug 25, 2014 at 19:08

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting idea! Did not know about wait.for, thanks! If I understand correctly, this "simulates" sequential programming without completely blocking node's event loop, right?
Yes, it allows you to call async functions and "wait" for the callback. It's like async/await, without the explicit "async". Any standard async function is "awaitable" with no changes required.
0

The node way of doing this would be something like this:

db.query(queryString, callbackproc);

function callbackproc(resultSet) {
  // do both cases here
}

1 Comment

On the second pass, the data is already there and I don't need to execute the query again, so I can't rely entirely on the post-query callback to compute my data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.