Node. js loop traps and node. js loop traps

Source: Internet
Author: User

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 );})})




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.