Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

javascript - JavaScript,Node.js:Array.forEach是否异步?(JavaScript, Node.js: is Array.forEach asynchronous?)

I have a question regarding the native Array.forEach implementation of JavaScript: Does it behave asynchronously?(我对JavaScript的本机Array.forEach实现有疑问:它是否异步运行?)

For example, if I call:(例如,如果我打电话:)
[many many elements].forEach(function () {lots of work to do})

Will this be non-blocking?(这将是非阻塞的吗?)

  ask by R. Gr. translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, it is blocking.(不,它正在阻止。)

Have a look at the specification of the algorithm .(看一下算法规格 。)

However a maybe easier to understand implementation is given on MDN :(但是,在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);
    }
  };
}

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);
}

and then call it with:(然后调用:)

processArray([many many elements], function () {lots of work to do});

This would be non-blocking then.(那时这将是非阻塞的。)

The example is taken from High Performance JavaScript .(该示例摘自High Performance JavaScript 。)

Another option might be web workers .(另一个选择可能是网络工作者 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...