I’m trying to create a small javascript framework that can make it easier when dealing with a third party library. This library is primarily asynchronous, so for example to establish a connection you would use the code:
var com = establishConnection("api-key");
com.onsuccess = function(c) {
c.submit("something");
};
What I want is to be able to use my wrapper framework to be able to simply do
var com = establishConnection("api-key");
com.submit("something");
Obviously though I need a way to handle the asynch nature of the original library, so it will wait until the connection is established before carrying out the commands. I know I can do something like set a flag to say whether or not the connection is established and then use some kind of looping delay, ie
function submit(msg) {
while (!connectionEstablished) {}
// do submit stuff
}
but it seems like such an ugly hack, does anyone have any advice for nicer ways to do this?
That would be the only way to convert an asynchronous request to a synchronous request.
Yes, it looks horrible, and ugly; because it is.
I know I don’t know the full in’s and out’s of your library, but I would suggest you (and your users) should embrace asynchronous requests rather than trying to mask them. HTTP requests are asynchronous in JavaScript for a reason; they don’t lock up the browser. Synchronous requests completely lock up the browser for the duration of the request. If you’re not careful, if the HTTP request is too long, your users will get an alert on most browsers saying to them that the script has stopped executing; and offer them the option to disable the script.