0

I'm a PHP programmer and I started developing with NodeJS to optimize my web application and reduce server resources.

I'm no expert in Javascript, therefore, I have several doubts in syntax and code.

I developed the following code:

var redis = require("redis"), client = redis.createClient();

client.on("error", function (err) {
    logger.error("Couldn“t connect Redis");
});

client.on("connect", function() {
    client.get("user:ID", function (err, reply) {
        if(reply) {
            // CODE       
        }
    });
});

I want that to continue executing the code when there is no key and I think putting various IF not the most optimized way.

EXAMPLE:

client.on("connect", function() {
    client.get("user:ID", function (err, reply) {
        if(reply) {
            // ROUTINE      
        }
    });
});

or

client.on("connect", function() {
    client.get("user:ID", function (err, reply) {});
});

if (key) {
    // Code 1
}

// Code

if (key) {
    // Code 2
}

............

Does something similar to php DIE to finish the routine? How could develop and optimize this? Thank you.

Regards

Anto
  • 313
  • 1
  • 3
  • 13

1 Answers1

0

I assume, you want to avoid nested callback.

Take a look How to avoid long nesting of asynchronous functions in Node.js

And I suggest following topics to get better knowledge of asynchronous nature of javascript

  • setTimeout and setInterval
  • Asynchronous ajax
  • process.nextTick()
  • Callback functions

Note: There is no function in Node.js like die(). If you want to do debug, you can use process.exit(). But this function terminate your web server. There is one more way, you can throw custom error and catch it. By do this, you can prevent the server process further on serving current request.

Community
  • 1
  • 1
HILARUDEEN S ALLAUDEEN
  • 1,722
  • 1
  • 18
  • 33