javascript - node.js redis 异步性质令人困惑

标签 javascript node.js redis

我正在如下使用 redis,遇到问题是因为 on('message') 似乎被异步调用了吗?

var subscriber = redis.createClient(port, host);
subscriber.subscribe('something');

subscriber.on('message', function(channel, message) {
    console.log('got message');

    // I use generator here

    var generator = myGenerator();
    var waitFunciton = generator.next().value;

    waitFunction(function(err, data) {

        var result = generator.next().value;

        // do something with result
        console.log('returning result');
    });

});

我希望看到

'got message'  
'returning result'
'got message'  
'returning result'

按顺序。

有时我会看到以下内容

'got message'
'got message'
'returning result'

看到缺少'返回结果',程序卡住了。

我该如何修复程序?

** 编辑 **

var myGenerator = function* (arg) {
    main = {};
    main.messenger = new Backbone.Model();

    // performs something heavy

    // at the end of the heavy work,
    // main.messenger.trigger('done') is called

    _.extend(main, {
        wait: function (callback) {
            return main.messenger.once('done', callback);

        }
    });

    yield _.bind(main.wait, main);

    // since I have results at hand I'm returning result next time when I'm called

    var result;

    return result;

}

最佳答案

您的代码卡住了,因为您在第一次调用 myGenerator 后仅触发了一次 donenext() 调用不会使生成器函数从头开始执行,因此带有 log('returning result')callback 只执行一次。

您可以修改您的 main.wait 函数来检查您的繁重计算是否已经完成并立即调用回调。

var myGenerator = function* (arg) {
    main = {};
    main.messenger = new Backbone.Model();

    // performs something heavy

    // at the end of the heavy work,
    // main.messenger.trigger('done') is called
    // main.messenger.set('computationDone', true);

    _.extend(main, {
        wait: function (callback) {
            if (main.messenger.get('computationDone') === true){
                 callback(); //filled with some data of course
            } else {
                return main.messenger.once('done', callback);
            }
        }
    });

    yield _.bind(main.wait, main);

    // since I have results at hand I'm returning result next time when I'm called

    var result;

    return result;
}

关于javascript - node.js redis 异步性质令人困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33822806/

相关文章:

javascript - 理解 Angular Directive(指令)

node.js - 使用 mocha 进行测试时,reSTLer 出现 "done() called multiple times"错误

node.js - typescript 错误中的字符串枚举

powershell - 是否可以在 Powershell 中处理 Get-AzureManagedCache 异常?

linux - 我应该禁用还是启用透明大页以提高性能吗?

javascript - 在 HTML Canvas 上绘制自相交多边形

javascript - body.scrollTop 在 firefox 和 IE 中不起作用 当在 Blogger 中时

javascript - 如何向 VueJS 中的某个元素指出这一点?

javascript - 通过express发送一个对象及其父类

caching - 在不使用持久性的情况下,Redis 在多个主服务器上进行分片会变得更快吗?