Skip to content Skip to sidebar Skip to footer

Javascript Design Patterns -- Dealing With Unwanted Asynchrony

I'm pretty new to event-based programming (using node.js). I believe that there's something I'm just not grokking about it, because there's a particular problem that I keep coming

Solution 1:

You are struggling with asynchrony because you are still writing your functions in a synchronous paradigm.

In asynchrony you should attach callbacks to events. You shouldn't expect a result from an asynchronous function like get_latest_results(), but you should pass it a callback function as an argument to be invoked when the results are ready. The callback will do whatever needs to be done with your results:

var get_latest_results = function (feedId, readyCallback) {
    client.get('feed:' + feedId + ':latest', function (err, res) {
        var latest_reading_key = res.toString();
        client.hgetall(latest_reading_key, function (err, res) {
            readyCallback(res);                           //--- Trigger Callback
        });
    });
    // how do I specify a return value for this function? //--- You don't
}

Then you can call your function like this:

get_latest_results(1000, function (result) {
   //--- Do whatever needs to be done with the latest result...
});

Post a Comment for "Javascript Design Patterns -- Dealing With Unwanted Asynchrony"