2013-06-21 57 views
0

我必须为我计算一些操作,但是我不能使用它的结果,因为我总是停留在等待状态,实际上我的终端仍然在执行我的程序直到我输入ctrl + C。MongoJS中没有阻塞操作

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

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; 

回答

2

欢迎异步世界! :)

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

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

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

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