JavaScript中,Node.js的:是Array.forEach异步? [英] JavaScript, Node.js: is Array.forEach asynchronous?
问题描述
我有一个关于本地 Array.forEach
JavaScript实现的一个问题:它是否表现异步?
例如,如果我称之为:
I have a question regarding the native Array.forEach
implementation of JavaScript: Does it behave asynchronously?
For example, if I call:
[many many elements].forEach(function () {lots of work to do})
这会不会是非阻塞?
Will this be non-blocking?
推荐答案
没有,它阻止。看看算法的规范。
No, it is blocking. Have a look at the specification of the algorithm.
然而一个也许更容易理解的实现是在<一个给定的href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\">MDN:
However a maybe easier to understand implementation is given on MDN:
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
fun.call(thisp, t[i], i, t);
}
};
}
如果您需要执行很多code的每个元素,你应该考虑使用不同的方法:
If you have to execute a lot of code for each element, you should consider to use a different approach:
function processArray(items, process) {
var todo = items.concat();
setTimeout(function() {
process(todo.shift());
if(todo.length > 0) {
setTimeout(arguments.callee, 25);
}
}, 25);
}
,然后调用它:
processArray([many many elements], function () {lots of work to do});
这是非阻塞即可。这个例子是从拍摄的高性能的JavaScript 的。
This would be non-blocking then. The example is taken from High Performance JavaScript.
另一种选择可能是的网络工作者的。
Another option might be web workers.
这篇关于JavaScript中,Node.js的:是Array.forEach异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!