小编典典

JavaScript、Node.js:Array.forEach 是异步的吗?

javascript

我有一个关于Array.forEachJavaScript 的本机实现的问题:它的行为是异步的吗?例如,如果我打电话:

[many many elements].forEach(function () {lots of work to do})

这将是非阻塞的吗?


阅读 143

收藏
2022-04-29

共1个答案

小编典典

不,它正在阻塞。看看算法的规范

然而, 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);
    }
  };
}

如果您必须为每个元素执行大量代码,则应考虑使用不同的方法:

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

另一种选择可能是web workers

2022-04-29