Skip ke Konten
Menu
Pertanyaan ini telah diberikan tanda
1 Balas
226 Tampilan

I'm trying to develop a module in Javascript and I try to generate rpc calls to query odoo database. I'm trying to do some calls from differents functions like that "obtener_id_empleado" and I'm trying to return the result to the main function but I always obtain undefined. Why?


In the ​console.log(result) I obtain an array of database data, but after the return and the assignment in console.log(empleado) I obtain undefined. I understand that is because rcp call is async, but I don't know how to wait until the rcp call is finished and call get right value.



willStart: function () {

            var self = this;

​    ​   var empleado = 0;

            empleado = this.obtener_id_empleado();

            console.log(empleado);  

 },


obtener_id_empleado: function(){

​rpc.query({

                model: 'hr.employee',

                method: 'search_read',

                args: [[['user_id', '=', this.getSession().uid]], ['name','id']],

​        ​context: session.user_context,

            })

            .then(function(result) {

​​console.log(result);

​​return result;

            });

},


Thanks

Avatar
Buang
Jawaban Terbai

Hi Santiago Carbonell Forment ,

The issue in your code is that you're not properly handling the asynchronous nature of the RPC call. When you call this.obtener_id_empleado(), it starts the RPC query, but doesn't wait for it to complete before continuing execution. The function returns undefined immediately because there's no return statement in the main function body.

try using async/await, and let me know if this works :)

willStart: async function () {
    var self = this;
    
    try {
        var empleado = await this.obtener_id_empleado();
        console.log(empleado);
        // Continue with your code using empleado here
    } catch (error) {
        console.error("Error fetching employee:", error);
    }
},

obtener_id_empleado: function() {
    return rpc.query({
        model: 'hr.employee',
        method: 'search_read',
        args: [[['user_id', '=', this.getSession().uid]], ['name','id']],
        context: session.user_context,
    });
}

Avatar
Buang