javascript - Node.js - 多轮并行 io

标签 javascript node.js io

我最近参加了一个 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/

相关文章:

Java 没有正确写入文件

javascript - 预加载显示/隐藏div

javascript - Google-apps-script 不会在 onEdit 函数内发送电子邮件

c - 给 read() 一个起始位置

java - 为什么我收到 "Exception in thread "main"java.lang.NumberFormat : null. . ."after clicking the "cancel"按钮?

java - 使用nio写入GZIP文件

javascript - 为什么当我删除搜索字段中的输入太快时,结果不会消失? (Javascript)

Javascript:将变量传递给 Google Charts API

sql - TypeORM:列必须出现在 GROUP BY 子句中或在聚合函数中使用

javascript - 当某个延迟部分(例如 setTimeout 或 process.nextTick)中发生异常时,使用 J2V8 的 Java 应用程序会崩溃