使用forEach时,与node.jsasynchronousstream程混淆。
我在node.js中编写了6个月。 我已经阅读了有关asynchronous编码,事件循环和callback等概念。 我知道“在同步代码栈执行时,asynchronous代码永远不会执行,这就是node.js是单线程的意思。 但是这只是一个例子
var a = [4, 5, 6, 7]; var results = []; a.forEach(function(result){ results.push(result + 1); }); console.log(results);
据我所知,函数forEach的参数是在同步块完成执行后调用的callback函数。 这意味着我期望的结果将是
[]
但它是事实
[5, 6 ,7, 8]
为什么发生这种情况? 是为了每个同步? 或者我错过了什么? 根据我的理解,
console.log(results)
将数据压入之前执行。
某些function是同步的,其他的是asynchronous的。 实际上,Array.forEach方法和所有的基本function是同步的。 如果你想asynchronous操作数组,你有两个select:在forEach中调用函数,但是你不知道什么时候完成,或者使用asynchronous库 。
第一种方法:
var a = [4, 5, 6, 7]; var results = []; a.forEach(function(result){ (function(i){ results.push(i); }(result+1)); }); console.log(results);
通过async.js:
var async = require('async'); var a = [4, 5, 6, 7]; var results = []; async.eachSeries(a, function(result, done) { results.push(result+1); done(); }, function () { console.log('forEach finished'); }); console.log(results);
传递给Array.prototype.forEach()
的callback是同步的。 因此,它将阻止执行线程,直到完成将该函数应用于数组的所有成员。
如果你想进一步研究JavaScript的asynchronous特性,我也设法find一些有趣的读法:
-
MDN – Array.prototype.forEach()
-
JavaScript,Node.js:是Array.forEachasynchronous?
这个线程解决了你当前面临的相同场景,它也提供了一个
Array.prototype.forEach()
的asynchronous替代scheme。 -
所有的JavaScriptcallback是asynchronous的吗? 如果没有,我怎么知道哪些是?