In node. js, is forEach () synchronous or asynchronous? _ node. js

Source: Internet
Author: User
This article mainly discusses and verifies whether forEach () in node. js is synchronous or asynchronous, and shares ideas and methods with you. if you need it, you can refer to it. Almost all callback functions in node are asynchronous. the code behind the callback function may be executed before the code in the callback function is executed, especially for database operations. Of course, node also provides functions for synchronous versions, such as file operations. fs. readFileSync () is the synchronous version of fs. readFile.

So the question is, is forEach () asynchronous? It should be asynchronous if Sync is not added.

The code is as follows:


Var arr = ['A', 'B', 'C'];
Var str = '20140901 ';
Arr. forEach (function (item ){
Str + = item;
While (true) {}; // use an endless loop and kill it ~~
});
Console. log (str );

Run the above code, and the result is so stuck that there is no output ..

Therefore, forEach () in node is synchronized !!

When I used node for the first time, I did not take this issue into consideration. I wrote it synchronously. I suddenly thought that after the test, I was shocked and thought that all the previous code was wrong.

In some cases, if forEach needs to be processed asynchronously, Google will have a node-array. you can try it ~~ Transport: https://github.com/cfsghost/node-array

This file is created at 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.