Cyclic traps in the Nodejs

Source: Internet
Author: User

The asynchronous mechanism of node. JS is implemented by events and callback functions, and it may feel like a violation of the routine at first, but the habit will find it simple.

However, there are a lot of traps in this, a very easy problem is to return to the loop callback function.

eq

var fs=require (' FS '); var files=[' 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 results of the actual operation are as follows:

[' A.txt ', ' b.txt ', ' c.txt ']3undefined[' a.txt ', ' b.txt ', ' c.txt ']3undefined[' a.txt ', ' b.txt ', ' c.txt ']3undefined
Here's how to fix it:

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




Cyclic traps in the Nodejs

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.