Summary of my NodeJs learning (1)

  • 2020-03-30 03:30:03
  • OfStack

  This first article will cover some programming details of NodeJs.

1. Go through the groups

for (var i=0, l=arr.length; i<l; i++)

          One benefit of writing this way is that it takes one less step per loop to get the length of the array object. The longer the array, the more significant the value.

2. Judge whether the variable is true or false

if (a) {...} //a='', a='0', a=[], a={}

          The results of the if condition are false, true, true, and true. This result is not the same as PHP's, so don't confuse it. We also need to distinguish between cases where it is similar to a non-identical judgment.

3. The value of 0 is not identical

1 if (0 == '0') {...} //true
2 if (0 == []) {...} //true
3 if (0 == [0]) {...} //true
4 if (0 == {}) {...} //false
5 if (0 == null) {...} //false
6 if (0 == undefined) {...} //false

          There are many more of these bizarre judgments, and I've listed only the more common ones. If you want to understand the rules, see my other post: [JavaScript] for an in-depth look at JavaScript's relational operations and if statements.

4. ParseInt traps

var n = parseInt(s); //s='010'

              The n value after the statement is executed is 8, not 10. Although many people know this, it's hard not to make mistakes in programming, as I know. So, it's best to write it the way it's written, so you don't make any mistakes.

var n = parseInt(s, 10);

5. Variables must be declared before they are used

          Although you can't go wrong by simply using variables without declaring them, writing in this way is very error-prone. Because the interpreter interprets it as a global variable, it can easily be misnamed with other global variables. So make it a habit to declare variables before you use them.

6. There is asynchrony in the loop

for (var i=0, l=arr.length; i<l; i++) {
   var sql = "select * from nx_user";
  db.query(sql, function(){
    sys.log(i + ': ' + sql);
  }); //Db.query is an asynchronous operation for a table query

          You'll see that the output is the same, and the output is the same when I = arr.leng-1. Because JavaScript is single-threaded, it performs a full loop of synchronous content before performing the asynchronous operation. The anonymous callback function in the code is an asynchronous callback. By the time you reach this function, the for loop and the rest of the synchronization is complete. Because of the closure principle, this function retains the contents of the SQL and I variables from the last loop of the for loop, which results in the wrong result.

          So what do we do? There are two solutions, one is to use the immediate function, as follows:

for (var i=0, l=arr.length; i<l; i++) {
  var sql = "select * from nx_user";
  (function(sql, i){
    db.query(sql, function(){
      sys.log(i + ': ' + sql);
    }); //Db.query is an asynchronous operation for a table query
  })(sql, i);

            Another method is to extract the asynchronous operation part, write a single function, as follows:

var outputSQL = function(sql, i){
   db.query(sql, function(){
      sys.log(i + ': ' + sql);
  }); //Db.query is an asynchronous operation for a table query

for (var i=0, l=arr.length; i<l; i++) {
  var sql = "select * from nx_user";
  outputSQL(sql, i); 

7. When processing large amounts of data, try to avoid loop nesting.

          Because the processing time of loop nesting increases exponentially with the amount of data, it should be avoided. In this case, if there is no better way, the general strategy is to use space for time, that is, to create a Hash map of the secondary loop data. Of course, still want specific case specific analysis. It is also important to note that some methods, such as array.sort () (which should be implemented with two layers of loops), are themselves looping bodies and should be used with care.

8. Avoid recursive calls.

          The advantages of recursive call are simple code, simple implementation, and its disadvantages are very important, as follows:

          (1) the size of the function stack increases linearly with the recursive level, while the function stack has a upper limit value. When the recursion reaches a certain number of levels, the function stack will overflow, resulting in program errors;

          (2) each recursive layer will add additional push and push operations, that is, save the scene and restore the scene during the function call.

          Therefore, recursive calls should be avoided as much as possible.

9. Scope isolation of module files.

          When compiling the JavaScript module file, Node has implemented the header and tail packaging of its contents, as follows:

(function(exports, require, module, __filename, __dirname){
   your JavaScript File code 

This enables scope isolation between each module file. So, when you write a NodeJs module file, you don't need to add another layer of scope isolation encapsulation yourself. The following code format, which adds an additional layer of function calls, is not recommended:

  ... ...

  Don't mix arrays and objects

          Here is an example of the error code:

var o = [];
o['name'] = 'LiMing';

          Mixing arrays and objects can cause unpredictable errors. One of my colleagues had a very strange problem, which was to look at the code:

var o = [];
o['name'] = 'LiMing';
var s = JSON.stringify(o);

            He expected the name attribute of object o to be in the JSON string, but it was not. I was also very strange at the time, but I had a hunch that it was a problem with arrays and objects, tried it, and it was. I later looked up in the ECMA specification that arrays were serialized according to JA. So, to develop a good programming habit, the correct use of arrays and objects, do not mix.

Promise programs gracefully

            Anyone who has worked with nodeJs has experienced that when asynchronous callbacks are nested within asynchronous callbacks, the code can be confusing and unreadable. NodeJs's dilemma can be overcome with promise. Promise is a tool to make your code elegant and beautiful. Promise has an A+ specification, which is available online in several ways.

Related articles: