phadaphunk
phadaphunk

Reputation: 13273

How can I wait for promises in a Socket.IO context

I have this setup

//Client Side


 socket.emit('some_event');


//Server Side


 socket.on('some_event', function(data){
      socket.emit('another_event', getDataFromAPI());
 });

The thing is that my function getDataFromAPI() is a call that could take some time since it calls an external API and it uses promises. Something like that :

function getDataFromAPI(){
   myAPI.getStuffFromId('123456789')
   .then(function(data){
         return data;
   });
 }

If I use it this way, there will be nothing in the getDataFromAPI() in the socket.IO call scope which sends null to the client and prints undefined if I decide to print it. If I log it into the console inside the promise then I have data but it's a bit too late to return it.

Since I will be using promises call with that API a lot and most of my client / server real time communication will be made through Socket.IO is there something obvious that I am missing or is this simply a pattern I should not be using.

Upvotes: 0

Views: 2275

Answers (1)

Bert
Bert

Reputation: 82439

Return the promise from your getDataFromAPI method.

function getDataFromAPI(){
   return myAPI.getStuffFromId('123456789')
     .then(function(data){
         return data;
     });
}

And emit when the promise is resolved.

io.on('connection', function(socket){
   socket.on('some_event', function(data){
      getDataFromAPI().then(function(apiData){
          socket.emit('another_event', apiData);
      })
   });
});

Upvotes: 5

Related Questions