gpt4 book ai didi

javascript - Node.js - 多轮并行 io

转载 作者:搜寻专家 更新时间:2023-11-01 00:08:46 25 4
gpt4 key购买 nike

我最近参加了一个 node.js 聚会,演讲的人说了一些类似的话:
“您需要生成器才能执行多轮并行 io。回调不会削减它”

我是 node.js 的新手,不知道这意味着什么。有人可以解释一下吗?

编辑:如评论中所问,这里有一个更详细的版本:我参加了一个介绍 node.js 的聚会。听众中有人问演讲者他认为 node.js 最大的缺点是什么。他说,在 node.js 获得生成器之前,它没有针对多轮并行 I/O 的良好解决方案。任何大型网络应用程序都必须这样做。多轮并行命中内存缓存是一个例子,数据库和第三方 API 是其他例子。任何来自 Python、Ruby 或 Go 等支持生成器、线程或微线程的语言的人都很难接受一个平台可以完全依赖回调。

最佳答案

他可能指的是序列助手,在下一个任务的回调中运行一个任务意味着链将同步运行。

这是我用来将大量数据插入 Mongo 集合的生成器示例。这会生成要并行执行的操作序列。在这种情况下,通过使用回调方法链接它们来执行一百万次插入并不是很实际。所以这就是我使用如下所示的生成器/序列助手的原因。

var Inserter = function (collection) {
this.collection = collection;
this.data = [];
this.maxThreads = 30;
this.currentThreads = 0;
this.batchSize = 1000;
this.queue = 0;
this.inserted = 0;
this.startTime = Date.now();
};

Inserter.prototype.add = function(data) {
this.data.push(data);
};

Inserter.prototype.insert = function(force) {
var that = this;
if (this.data.length >= this.batchSize || force) {
if (this.currentThreads >= this.maxThreads) {
this.queue++;
return;
}
this.currentThreads++;
console.log('Threads: ' + this.currentThreads);
this.collection.insert(this.data.splice(0, this.batchSize), {safe:true}, function() {
that.inserted += that.batchSize;
var currentTime = Date.now();
var workTime = Math.round((currentTime - that.startTime) / 1000)
console.log('Speed: ' + that.inserted / workTime + ' per sec');
that.currentThreads--;
if (that.queue > 0) {
that.queue--;
that.insert();
}
});
}
};

关于javascript - Node.js - 多轮并行 io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17012134/

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