【问题标题】:how to wait the end of the execution of a function如何等待函数执行结束
【发布时间】:2023-03-21 07:12:02
【问题描述】:

我的程序有一个 main in 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
       }
    });

    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,您还必须使用另一种方法。有关更多信息,请参阅stackoverflow.com/a/14220323。示例使用 Ajax,但概念仍然适用。

标签: node.js mongodb mongojs


【解决方案1】:

您必须像 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);
});

【讨论】:

    【解决方案2】:

    在异步 JS 中,您无法按照您想要的方式返回值。您需要在调用 gestionar.gestion() 时从主程序中传递一个回调函数(您可以将其添加为第三个参数)。

    您的代码示例将不起作用,因为函数 gestion() 在设置 intervalo_final 内容之前立即返回。

    类似这样的:

    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/

    【讨论】:

      猜你喜欢
      • 2022-07-01
      • 1970-01-01
      • 2019-01-31
      • 2021-01-23
      • 2018-01-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2019-01-06
      相关资源
      最近更新 更多