0

I'm taking data from SIGNALR Hub with JavaScript client and works well, but I need simulate synchronous in some cases. For instance, taking parameters from a database, in a For Loop in my JavaScript client. Here is my javascript simplified

var results = []; // empty array to hold results

function test(){
var list = ['item 1','item 2,'item3',item 4']
    for(var i = 0;i<list.length;i++){
        // call to signalr hub
         $.connection.hub.start().done(function(){
            bip.server.getString( list[i] ).done(function(x){
              results.push(x)});
        });
       // end call signalr hub
    }
}

Obviusly, it doesn't work, function test() returns before hub server response populates the array results in done(). signalr returns a deferred object when calling bip.server.getSTring(...); but, server returns value on .done() that also is a deferred object.

My question is : How can I avoid javascript function exists before .done(... does his job.

TResponse
  • 3,940
  • 7
  • 43
  • 63
  • No, you don't want synchronous behavior. Instead, you want to [wait for multiple deferreds](http://stackoverflow.com/q/5627284/1048572). – Bergi Jan 24 '15 at 20:38

1 Answers1

0

Try this:

Declare your list, result and a index to keep track of your array

var results = []; // empty array to hold results
var list = ['item 1','item 2,'item3',item 4']
var currentndex = 0;

Start your hub and register a client response handler

function start()
{
   // register client callback for when it comes back from the server
   $signalrhubs.hub.client.serverResponse

   // do other initializing stuff
   $.connection.hub.start().done(callServer);

}

Call your server when ready, check the index against the length of the array and increment it.

function callServer()
{         
     if(currentIndex <= list.length)
     {
         bip.server.getString( list[currentIndex ]);                
         currentIndex += 1;
     }
}

When you get the response add the result and call the server again

function serverResponse(x)
{
     results.push(x)
     callServer();
}
TResponse
  • 3,940
  • 7
  • 43
  • 63