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');
开发者_StackOverflow};
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 to false
, it will make it synchronous instead of asynchronous:
var qqq=0;
function init(){
var requestClient= Ti.Network.createHTTPClient();
requestClient.open('GET','https://mysite.com/api/123/id/5/friends', false);
// Here------^
requestClient.onload = function() {
alert('loaded');
};
requestClient.send();
};
init();
alert(qqq);
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 init
accept a callback you call from within the onload
handler, as this makes for a much better UX:
var qqq=0;
function init(callback){ // <== Accept a callback
var requestClient= Ti.Network.createHTTPClient();
requestClient.open('GET','https://mysite.com/api/123/id/5/friends');
requestClient.onload = function() {
alert('loaded');
callback(); // <== Call the callback
};
requestClient.send();
};
init(function() { // <== Pass the callback into `init`
alert(qqq);
});
Effective web programming is about embracing the event-driven nature of it. I'd strongly recommend the second example.
精彩评论