JavaScript Design Patterns — Dealing With Unwanted Asynchrony

前端 未结 1 1330
庸人自扰
庸人自扰 2021-01-04 02:18

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 k

相关标签:
1条回答
  • 2021-01-04 02:53

    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...
    });
    
    0 讨论(0)
提交回复
热议问题