Jump to content

Problem with callback.


Teleconocimieto

Recommended Posts

Hello.

I have a problem with a function that contains a callback. The problem is, when I execute it the first time, it works without no problem, but the second time, the callback is executed twice: first with the first value and later with the second value.

 

I post the code and an example of running

 

Code of the function:

function titulo(terminoTitulo) {      console.log("titulo():");      console.log("titulo(): Fuera del callback: " + terminoTitulo);      consultar_titulo(terminoTitulo, function (titulo) {          console.log("titulo(): termino: " + terminoTitulo);          console.log("titulo(): Dentro del Callback");          console.log("titulo(): "+titulo.length);      });

Code of the proxy that receives the parameters and calls to a nodejs server:

function consultar_titulo(titulo_consulta, callback) {    var socket = io.connect('http://localhost:8080');    socket.emit('consultar_titulo', {        "titulo_consulta": titulo_consulta    });    console.log("proxy(): Emitida la consulta");    socket.on('respuesta_consultar_titulo', function (data) {        console.log("proxy(): Estoy en el proxy dentro del callback");        callback(data.respuesta_emit);    });} //consultar_titulo()

Example of running.

titulo():titulo(): Fuera del callback: bbb proxy(): Emitida la consulta proxy(): Estoy en el proxy dentro del callback titulo(): termino: aaa titulo(): Dentro del Callback titulo(): 0 proxy(): Estoy en el proxy dentro del callbacktitulo(): termino: bbb titulo(): Dentro del Callbacktitulo(): 0 
In this example the first time, the user introduced "aaa", and the second time "bbb".
As can see, the function is called once but when the callback is executed two times.
Regards
Link to comment
Share on other sites

The callback is executed twice because the socket event happens twice. The line "proxy(): Estoy en el proxy dentro del callback" gets printed when the event fires, and that line gets printed twice. So, the event fires twice.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...