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