I want to have my own initialization function, and I want it exit only after onload event, what can I do for it?
var qqq=0;
function init(){
var requestClient= Ti.Network.createHTTPClient();
requestClient.open('GET','https://mysite.com/api/123/id/5/friends');
requestClient.onload = function() {
alert('loaded');
};
requestClient.send();
};
init();
alert(qqq);
Well, you can do that, by making the request synchronous instead of asynchronous. This has unpleasant side-effects on the user’s browsing experience, tending to lock things up during the request, but if you set
open‘s third argument tofalse, it will make it synchronous instead of asynchronous:A synchronous request will bring the JavaScript execution on the page (at least, and in many browsers rather more than just the JavaScript) to a screeching halt until the network operation completes.
But the usual practice is to have your
initaccept a callback you call from within theonloadhandler, as this makes for a much better UX:Effective web programming is about embracing the event-driven nature of it. I’d strongly recommend the second example.