2013-06-24 35 views
0

我在我的程序的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 
     } 
    }); 

    setTimeout(function(){ 
     console.log("pause"); 
    },3000); 
    console.log(intervalo_final); //result not correct 

return intervalo_final; 
} 

exports.gestion = gestion; 

我知道節點執行我的回報,而不等待我的函數結束時,爲了這個,我看不出正確的結果,但我怎麼能強迫我的程序等待我的功能結束? 我嘗試了setTimeout函數,但不是正確的方法。

+0

您的目標與您的代碼不一致。 'db.clientes.save()'是一個異步方法,「* waiting *」是同步的。除了'return'之外,你必須使用另一種方法。有關更多信息,請參閱http://stackoverflow.com/a/14220323/。這些示例使用Ajax,但這些概念仍然適用。 –

回答

0

在async JS中,您無法像您嘗試那樣返回一個值。調用gestionar.gestion()時,您需要從主程序傳遞一個回調函數(您可以將其添加爲第三個參數)。

您的代碼示例將不起作用,因爲在設置intervalo_final內容之前,函數gestion()立即返回。

事情是這樣的:

gestionar.gestion(myJSONClient,vector_intervalo, function callback(intervalo) { 
    // This is the callback function 
    console.log("intervalo: " + intervalo); 
}); 

再內的功能:

var gestion = function(myJSON,vector_intervalo, callback) { 
... 
db.clientes.save(cliente1, function(err, saveCliente) { 
    if (err || !saveCliente) { 
     console.log("Client "+cliente1.nombre+" not saved Error: "+err); 
     if (callback) callback(); // execute callback function without arguments 
    } 
    else { 
     console.log("Client "+saveCliente.nombre+" saved"); 
     intervalo_final = calculate(vector_intervalo); 

     console.log(intervalo_final); 

     if (callback) callback(intervalo_final); // your callback function will be executed with intervalo_final as argument 
    } 
}); 

另外,我強烈建議您閱讀一些異步JavaScript的教程,像http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

和Felix的Node.js的指南:http://nodeguide.com/

1

你mus t像API中的其他異步函數一樣實現你的函數! 第一步:給回調函數

var gestion = function(myJSON,vector_intervalo, callback) { 

第二步:當異步過程結束調用回調函數傳遞的結果(你不需要回線)

console.log(intervalo_final); //here I can see... 
callback(intervalo_final); 

第三步:使用您的功能以異步的方式運行

gestionar.gestion(myJSONClient,vector_intervalo, function(result){ 
    console.log(result); 
});