Cyclic traps in the Nodejs

Source: Internet
Author: User
Tags readfile

The asynchronous mechanism of Node. JS is implemented by events and callback functions, which may feel like a violation of the routine, but the habit will find it very easy to get Started.

There are, however, many pitfalls in This. A very easy problem to encounter is to go back to the callback function of the Loop.

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 execution are as Follows:

[' a.txt ', ' b.txt ', ' c.txt ']3undefined[' a.txt ', ' b.txt ', ' c.txt ']3undefined[' a.txt ', ' b.txt ', ' c.txt ']3undefined
The workaround 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);    })})




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.