JavaScript、Node.js:Array.forEach 是异步的吗? [英] JavaScript, Node.js: is Array.forEach asynchronous?

查看:27
本文介绍了JavaScript、Node.js:Array.forEach 是异步的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 JavaScript 的原生 Array.forEach 实现的问题:它的行为是异步的吗?例如,如果我调用:

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

这会是非阻塞的吗?

推荐答案

不,它正在阻塞.查看算法规范.

No, it is blocking. Have a look at the specification of the algorithm.

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

然后调用它:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆