1

I'm initializing a page using multiple WebSocket queries (I receive the results via the onmessage event and then call the right callback function for each message I receive).

i.e:

query("get_users",callback1);
query("get_weather",callback2);
...

Now I want to display a loader (spinner) and make it disappear only after all the data has been loaded (all callbacks are done). I know that I can make the callbacks update a counter, but I'm looking for a more elegant way to do this, if possible.

I tried using JQuery Promises but couldn't understand how to use it with WebSockets (instead of Ajax calls).

please help.

0

1 Answer 1

2

Promisify it:

function request(url){
 return new Promise(function(resolve){
   query(url,resolve);
 });
}

Then you can use Promise.all:

Promise.all([request("get_users"),request("get_weather")])
 .then(function([users,weather]){
   console.log(users,weather);
});

If you want to seperate the data handler and the spinner, simply make the Promises globally available:

var users=request("get_users"),
  weather=request("get_weather");

weather.then(function(weather){
  //show weather
});
//same with users

loader.show();//show some spinner
Promise.all([weather,users]).then(loader.hide);//hide if all loaded
Sign up to request clarification or add additional context in comments.

2 Comments

what if the queries are initiated from different files? (i.e: one file queries the users and handle the results, another file query the weather, etc...)
@OmriSoudry expose the promises to global variable, e.g. var weather=request("get_weather"); , then you can put it into Promise.all everywhere...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.