Node. js loop traps and node. js loop traps
The asynchronous mechanism of Node. js is implemented by events and callback functions. It may feel like a violation of the Conventions at the beginning, but it will be very easy to get used to later.
However, there are actually many traps hidden in this process. A very easy problem is to return to the loop callback function.
Eq:
Var fs = require ('fs'); var files00000000'a.txt', 'B .txt', 'c.txt']; for (var I = 0; I <files. length; I ++) {fs. readFile (file [I], 'utf-8', function (err, contents) {console. log (files); console. log (I); console. log (files [I]) ;}}
The actual running result is as follows:
Comment '] 3 undefined
The solution is as follows:
Var fs = require ('fs'); var files?}'a.txt', 'B .txt', 'c.txt']; files. forEach (function (filename) {fs. readFile (filename, 'utf-8', function (err, contents) {console. log (filename + ":" + contents );})})