【问题标题】:No blocking operation in MongoJSMongoJS中没有阻塞操作
【发布时间】:2013-06-18 23:10:37
【问题描述】:

我必须做一个为我计算一些东西的操作,但我不能使用它的结果,因为我总是处于等待状态,事实上在我的终端中我的程序一直在执行,直到我输入 ctrl+ C.

我的程序在 nodejs 中有一个 main,我需要使用在模块中计算的结果。

var myJSONClient = {
    "nombre" : "<nombre_cliente>",
    "intervalo" : [0,0]
    };


var intervalo = gestionar.gestion(myJSONClient,vector_intervalo); 
console.log("intervalo: "+intervalo); //return undefined

这是模块

var gestion = function(myJSON,vector_intervalo) { 
var dburl = 'localhost/mongoapp';
var collection = ['clientes'];
var db = require('mongojs').connect(dburl, collection );
var intervalo_final;

    function cliente(nombre, intervalo){
        this.nombre = nombre;
        this.intervalo = intervalo; 
    }

    var cliente1 = new cliente(myJSON.nombre,myJSON.intervalo);

    db.clientes.save(cliente1, function(err, saveCliente){
    if (err || !saveCliente) console.log("Client "+cliente1.nombre+" not saved Error: "+err);
    else console.log("Client "+saveCliente.nombre+" saved");
        intervalo_final = calculate(vector_intervalo);

        console.log(intervalo_final); //here I can see the right content of the variable intervalo_final

    });

console.log(intervalo_final); //this is not executed
return intervalo_final;
}

exports.gestion = gestion;

【问题讨论】:

    标签: node.js mongodb mongojs


    【解决方案1】:

    欢迎来到异步世界! :)

    首先,你没有在 Node 中做阻塞操作。实际上,Node 中的网络是完全异步的。

    您声明console.log 的部分起作用是因为db.clientes.save 调用的回调函数。该回调表明您的 mongo 保存已完成。

    什么是异步网络?
    这意味着您的保存将在未来的某个时间进行处理。该脚本不会等待响应继续执行代码。保存调用后的console.log 将在到达后立即执行。

    至于脚本的“等待状态”,它永远不会结束,你应该看看this question。这就是答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 2011-03-07
      相关资源
      最近更新 更多