Home  >  Article  >  Web Front-end  >  Is forEach() in node.js synchronous or asynchronous?_node.js

Is forEach() in node.js synchronous or asynchronous?_node.js

WBOY
WBOYOriginal
2016-05-16 16:17:211958browse

Almost all places in node that use callback functions are asynchronous. The code after the callback function is likely to be executed before the code in the callback function, especially database operations. Of course, node also provides synchronous versions of functions, such as file operations. fs.readFileSync() is the synchronous version of fs.readFile().

Then the question is, is forEach() asynchronous? Logically speaking, if Sync is not added, it should be asynchronous.

Copy code The code is as follows:

var arr = ['a', 'b', 'c'];
var str = '123';
arr.forEach(function(item) {
str = item;
While (true) {}; //Use an infinite loop to jam it~~
});
console.log(str);

Run the above code, and it gets stuck without any output. .

So, forEach() in node is synchronous! !

When I used node for the first time, I didn’t think about this problem. I wrote it synchronously. It suddenly occurred to me when I was writing it. After the test, I had a false alarm and thought that the previous code was written wrong.

If in some cases, you need to process forEach asynchronously, you can search on Google and there is a node-array, you can give it a try~~ Portal: https://github.com/cfsghost/node-array

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn