Skip to content Skip to sidebar Skip to footer

Event Emitter Synchronous Node.js Client Side

function findById(id) { var fullName = ''; client.emit('findById', id, function(result){ fullName = result.fullName; }); } I want find full name from function

Solution 1:

To make it synchronous, you have to lock up the function with a loop. I don't recommend doing this.

functionfindById(id) {
   var fullname, waiting = true;

   client.emit("findById", id, function(result){
       fullname = result.fullName;
       waiting  = false;
   });

   while (waiting);
   return fullname;
}

It's better to just embrace the fact the method is inherently asynchronous, and pass the result to a callback:

function findById(id, callback) {
   client.emit("findById", id, function(result){
       callback(result.fullName);
   });
}

Usage would then be:

findById(id, function(fullName) { /* ... */ });

If nested callbacks become a headache in your application, there are flow control libraries like async (runs in Node and in the browser) that make things cleaner and more readable.

Post a Comment for "Event Emitter Synchronous Node.js Client Side"