is the foreach () in the Node.js synchronous or asynchronous? _node.js

Source: Internet
Author: User

Almost every place in the node where the callback function is used is asynchronous, and the code behind the callback function is likely to be executed first, especially the database operation, after the code in the callback function. Of course, node also provides a synchronized version of a function, such as a file operation, and Fs.readfilesync () is a synchronized version of Fs.readfile ().

So the question is, is ForEach () asynchronous? Logically speaking, without sync, it should be asynchronous.

Copy Code code as follows:

var arr = [' A ', ' B ', ' C '];
var str = ' 123 ';
Arr.foreach (function (item) {
str = + Item;
while (true) {}; With a dead loop, stuck to it!
});
Console.log (str);

Run the above code, and it turns out to be so jammed, without any output.

So, the foreach in node is synchronized!!

The first time with node, did not consider this issue, according to the synchronization of the written, write suddenly thought, after testing a false alarm, thinking that the previous code has been written wrong.

If in some cases, need to asynchronous processing foreach, Google a bit, there is a node-array, you can try ~ ~ Transmission door: Https://github.com/cfsghost/node-array

This work is created by Http://www.cnblogs.com/ImYZF

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.