简体   繁体   中英

Finish the routine in NodeJS or Javascript

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM