Search code examples
javascriptnode.jsirc

Callback handler not concating string


I am using this code:

if (msg[0] == '!web')
{
    var result = '\x032[\x02status\x02]\x03 Web: ';

    checkPortTCP('127.0.0.1', 80, function() {
        result += JSON.stringify(this).slice(1, -1);
    });

    bot.say(channel, result);
}

When I type !web in my channel, the result is:

 [status] Web: 

Without the actual output.

checkPortTCP:

function checkPortTCP(host, port, cb)
{
    net.createConnection(port, host).on("connect", function(e) {
        cb.call("online");
    }).on("error", function(e) {
        cb.call("offline");
    });
}

I am making a status bot for IRC. Final result should be ... Web: Online/Offline

result += JSON.stringify(this).slice(1, -1);

should concat the result variable and then say it into my channel. But for some reason, it doesn't concat the string.

Thanks!


Solution

  • The problem occurs because checkPortTCP callback executes not right now, but in some delay, so it happens that in your example bot.say(channel, result); executes before result += ...

    Try to paste bot.say(channel, result); inside checkPortTCP callback. So it will be:

    var result = '\x032[\x02status\x02]\x03 Web: ';
    
    checkPortTCP('127.0.0.1', 80, function() {
        result += JSON.stringify(this).slice(1, -1);
        bot.say(channel, result);
    });
    

    Update

    If you want to check multiple services you may write something like following:

    checkPortTCP('127.0.0.1', 80, function() {
        result += JSON.stringify(this).slice(1, -1);
    
        checkPortTCP('127.0.0.1', 81, function() {
            result += JSON.stringify(this).slice(1, -1);
    
            bot.say(channel, result); 
        });
    });
    

    There is two services check, but you can have more. You just have to nest one check into another and in the last callback call bot.say method