gpt4 book ai didi

JavaScript,Node.js : is Array. forEach 异步?

转载 作者:IT老高 更新时间:2023-10-28 11:04:00 26 4
gpt4 key购买 nike

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

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

这会是非阻塞的吗?

最佳答案

不,它正在阻塞。看看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);
}
};
}

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

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

这将是非阻塞的。示例取自 High Performance JavaScript .

另一个选项可能是 web workers .

关于JavaScript,Node.js : is Array. forEach 异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5050265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com