0

I have to do an operation that calculate for me something, but I can't use the result of it, because I always stay in a wait state, in fact in my terminal remains in execution my program until I enter ctrl+C.

I have a main in nodejs for my program where I need to use my result calculated in a module.

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


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

And this is the module

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;
user2369478
  • 63
  • 11

1 Answers1

2

Welcome to the async world! :)

First of all, you aren't doing blocking operations in Node. Actually, networking in Node is fully asynchronous.

The part you state the console.log works it's because the callback function of the db.clientes.save call. That callback states your mongo save has finished.

What asynchronous networking means?
It means that your save will be processed sometime in the future. The script will not wait for the response to continue the code. The console.log right after the save call will be executed soon as it's reached.

As for the "wait state" of your script, that it never ends, you should take a look at this question. There's the answer.

Community
  • 1
  • 1
gustavohenke
  • 40,997
  • 14
  • 121
  • 129