Asynchronous Problem
Hi, i'm facing an asynchronous problem: the call to the function "DrawNews" is being executed before the xml is completely loaded into the XML obj... what's the way to deal with it?
/:NewsMenu = new XML(); /:NewsMenu.load("NewsDataSource.asp"); /:NewsMenu.onLoad = DrawNews;
Thanks in advanced, Maya.
FlashKit > Flash Help > Flash ActionScript
Posted on: 12-29-2002, 06:34 AM
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Asynchronous XML
Hello all,
I'm having a bit of an XML problem. I'm trying to get my XML to load before the rest of the script executes. The problems is, if I do something like the following, buildCalendar does not execute. Any suggestions?
myXML = new XML();
myXML.ignoreWhite = true;
myXML.onLoad = myOnLoad;
myXML.load("calendar.xml");
function myOnLoad(success) {
if(success) {
trace("Loaded XML");
xmlCreateArray();
} else {
trace("Error - Could not load XML file");
}
}
function xmlCreateArray() {
xmlArrayDate = new Array();
// loop array code here
buildCalendar()
}
function buildCalendar() {
// Prototypes
// calendar code here
trace("Hey there, I'm working.")
)
Is DuplicateMovieClip() Asynchronous Or Not?
Hello,
I am in my own personal hell trying to wrangle duplicateMovie() into submission. My code is straightforward:
while(i < howmany( {
// stuff
trace("hello from hither");
duplicateMovieClip("seed", "target", depth);
// stuff
i = 1 + i;
}
At frame 1 of the target movie I have:
trace("hello from yonder");
I was expecting the "hither" and "yonder" traces to interleave:
hither
yonder
hither
yonder
hither
yonder
...
Nope. First all the hithers then all the yonders appear. Huh? This implies that duplicateMovie(). Yes or no?
How do I make the traces interleave?
Cheers,
Douglass Turner
email: turner@landmat.com
Is LoadVariables() Asynchronous?
when loadVariables() is called, does it return before loading the variables?
i have the following script:
_root.loadVariables(url,0);
my_text_box = _root.param_from_url;
which doesn't work as expected. The first time the code is executed, nothing happens. The second time the code is executed, the text from the first time appears in the text box. And so on. Any ideas why this is happening?
thanks
Asynchronous Call
Hi,
how can I make an asynchronous call to a function.
I want to implement a search "thread" which should search.. but the user should still be able to type into the textfield. At the moment it is something like :
search_inputmask.onChanged = function()
{
...
setInterval(sendSearch,300)
...
}
which does not work.
How can I make this call not to stop flash reacting to user inputs?
Any ideas?
Philipp
Asynchronous Loops
I'm trying to use AS to add a series of buttons, and set the onPress property for each one. I've used a loop, but the loop seems to run through before the property is set. My code.
do {
_root.tback.attachMovie("blob", "blob"+f, 100+f);
this["blob"+f]._x = 50*f;
this["blob"+f].onPress = function() {
getURL(f+".htm");
};
f++;
} while (f<4);
So this adds three buttons, correctly positions them, BUT doesn't give them getURL 1.htm, 2.htm and 3.htm but instead gives all 3 getURL ("4.htm").
How can I make sure the correct urls are added before the loop continues?
Asynchronous XML Documents
Hi,
I'm fairly new to Flash and am not sure if Flash can handle the problem I am trying to solve or not, but if so, can someone point me to some examples or place where I can get more information? Many thanks in advance!
Here is what I would like to do...
I have an HTTP server that collects network information and asynchronously sends XML documents to various clients whenever the network environment changes. So far, all of my clients have been written using a combination of Java, HTML, XML, XSL, and JavaScript. I'd like to create a Flash client.
Right now, when a client is started, it opens a socket on the server and sends a special XML document that informs the server that it wants to receive asynchronous data. The server saves this socket and whenever it receives new data, it asynchronously sends an XML document to the client over this socket.
So, my questions are as follows:
Can I use Flash in this manner?
Do I use the same technique of opening a socket on the server to receive asynchronous XML documents or does Flash handle this a different way?
I've written a custom HTTP server using Java. Will my server require any special plugins or code to handle an asynchronous connection to the Flash movie? I'd prefer not to embed proprietary plugins on my server unless I can redistribute my software without paying royalties.
Do you have any examples a Flash app/movie that receives asynchronous XML documents from a server that I can view to get me started with this project?
Thank you very much. Please message me if you need clarification.
As3 + Asynchronous = Annoyance
Hey!
I remember working with AMFPHP in AS2 and arguing with MANY flash developers who praised asynchronous stuff within flash. Granted its a nice way to do things but from a progmatical point of view its a nightmare...
Let me explain my situation and problem a bit more...
I want to use AMFPHP and wrap up the service communication in classes, so its all handled via external .as files, this way to do communication via Flash + PHP i only need to include a package instansiate the given class then send over a service request.
In an ideal world here is how i would imagine it going:
Code:
// I would have an internal default gateway incase you dont want to set one...
var serviceCommunicator:amfService = new amfService(my_gateway);
// Once the objects created, i would call a function "runService(arg1,arg2)" this
// would then ideally do the connection, run the service, then return out an
// object with the data retrieved from the service.
var serviceResult:Object = serviceCommunicator.runService(my_service, my_params);
Now the code above seems fairly logical and easy to use to me, that way you would wrap up alot of the functionality internally in the amfService class and all you need to do is run 2 lines to communicate with PHP...
However due to it being async, when you call run service it has to point the service to 2 return functions one for success one for error, that instantly means that you cant return anything worth while from the runService function as that just sets up the callback functions.
At this point i thought there MUST be a way to get my response without having to make a loader movieclip in flash or having to do some nasty global variables which dump the object when complete.
So im trying to think of ways to do this, i was thinking of maybe making a timer and having a while loop in the runService function to see if it has had a response (good or bad) then return out the relevent data that way. The timer could check a boolean flag internally to see if the operation has completed then return out, however im SURE that flash holds on while statements so i dont think i can do it that way. Then i thought about making an event that fired, but thats just going to go from one callback to another... Every way i think of doing it seems blocked by something...
So does anyone who knows what im going on about have any advice or ways they have made this process run all from actionscript?
I know this kinda goes against the point of it being asynchronous however i dont like mixing functionality and design, they *should* always be kept seperate, and the only easy way i can think of doing this is to make some looping movie clip which checks if the class has finished its communication, if it has then it triggers a function and trips a flag so everything else knows what to do, either way it seems illogical and a bit too much work for something simple...
Over to you guys!
Help With Asynchronous Action
Hi People,
I having trouble coding the following:
- method "A" calls method "B" from another Class;
- method "B" initiates an asynchronous action(onEnterFrame verification);
- When the event initiated by method "B" is finished,method "B" should return a value to method "A" perform a logic comparison;
My problem is:
-----------------
how do I pass the value from the onEnterFrame event(when finished)
to its calling method(method "B" return statement) ?
How do I return the value from function "B" to function "A" correctly ? ( it always return "undefined" because function "B" calls an asynchronous action.
Thanks everybody
Asynchronous Code Execution
Hi,
the task is to go through textdata to search for a string inside it. Thats why this function blocks all other operation when I search inside a big text. Is there a way to call it asynchronous, so that it is not blocking operations?
Here the code, how the search starts:
code:
search_inputmask.onChanged = function()
{//starts timer, user dont have to press button, searching starts after 300ms
if(_global.waitingState == 0 || _global.waitingState == undefined)
{ _global.waitingState = setInterval(sendSearch,300); return; }
if(_global.waitingState != 0)
{ clearInterval(_global.waitingState); _global.waitingState = setInterval(sendSearch,300); }
}
function sendSearch()
{//sends searchstring to SearchEngine
clearInterval(_global.waitingState);
_global.waitingState = 0;
var resultSet = mySearchEngine.performSearch(search_inputmask.text ); //start the search
myResultarea.refresh(resultSet);
}
And here is a simplified version of a search loop. The blocking function is String.indexOf, because with bigger data this takes very long to go through.
code:
SearchEngine.prototype.performSearch = function(searchString)
{
...
for(var i=0; i<this.textData.length;i++)
{
var toCompare = this.textData[i];
var pos=0;
if((pos = toCompare.indexOf(searchString))!= -1)
{
this.resultSet.push(new Array(toCompare,i,pos)
}
}
...
}
return this.resultSet;
Philipp
Surely There Is A Better Way... (Asynchronous Rant)
Hey,
Ive been playing around with flash for a while now, and ive recently been bringing some stuff together from a project im working on, however ive just gotten to a section where i will have to daisychain about 8 functions together to do a fairly simple task... and im sat here thinking... surely there is a better way to do this... Here is the current scenario...
Ive got a main.swf file that deals with loading up other swf files internally, they all communicate via a static event handling class, and i made a custom event (SWFEvent) that deals with sending over small packets of information to let them communicate. They are not using any custom document classes, just the default ones that flash must generate within the swf file...
Now as you go through the various SWF files loaded the main.swf saves some of the data, such as unique ID and login times etc. Then finally once you have logged in and the main.swf has the required details set it loads up the final.swf file.
This file then has to do a small amount of tasks:
1) Load up an external config xml file
2) Use the data within the XML file to connect to the server
3) Once connected, Needs to send event to main.swf to get Unique ID stored within there
4) Once it retrieves the ID it sends it for validation to the server
5) Once validated it returns a shared object for the flash file to use
Now i thought this wouldnt be too hard, however i just thought of the simplest way to implement this, and it seems like a right mountain of functions.
1) I have to do a Loader request for the XML file, which then has 2 functions for onSuccess/onFailed. Providing the onSuccess function is called i can move onto task 2.
Current Functions: 2 (onSuccess/onFailed)
2) Then within the onSuccess function i will need to attempt a server connection with the XML details collected, this will then need an onSuccess/onFailed. Providing the onSuccess is called i can move onto task 3.
Current Functions: 4 addded (onSuccess/onFailed)
3) This needs to be split into 3 sub sections:
3-A) Within the previous onSuccess function i then need to send an event to the main.swf.
3-B) main.swf then needs to implement a listener for the swf communication event, when this function is called it then needs to respond to the final.swf file with the ID it has stored.
3-C) finally the final.swf needs to implement a listener for the returned event, once that is triggered it needs to move onto task 4.
Current Functions: 6 added (main.swf event, final.swf event)
4) This then sends the data to the server, which requires another onSuccess/onFailed function.
Current Functions: 8 added (onSuccess/onFailed)
5) Providing all the relevent onSuccess functions got to this point i then can start using the sharedobject, which im sure will need to implement other sync functions, but i guess at least this is a stopping point for the current scenario.
Current Functions: 8
Now as i work with other languages primarily actionscript is just a language im having to use on the side for projects, but it just seems so painful to do things. The above scenario that is used to just implement 1 sharedobject requires me to bloat my final.swf with 7 functions and add another to the main.swf. I dont really mind having all the functions but the thing that i dont like is the fact that they are all daisy chained. Each one calls the next, and so on, and eventually after linking a load of functions together i get 1 variable from a server.
Im hoping im just going about things the wrong way, but do any of you other actionscripters have to frequently do things like this? if so did you find any easier ways to do things than having to daisy chain masses of functions...
Maybe its just me, but regardless i thought i would make a post in the hope that someone can laugh at me and tell me im making a mountain out of a molehill and show me a simpler technique...
How To Create An Asynchronous Function
Hi all,
I'm writing an application that needs to do XML parsing, which takes a while and blocks the rest of my application. So I'd like to make my parsing function asynchronous. Any idea how async functions can be written ?
Regards,
Alex
LoadVars.send() Asynchronous?
Does anybody know if LoadVars.send() is asynchronous? I can't find it documented anywhere. sendAndLoad() is asynchronous, but that's (at least) because it has a load() method in there. I assume that send() is asynchronous, but it returns a 'success' value. At first glance, I'd assume it couldn't return a success value if it were asynchronous, but at second glance it might be that the success value is simply whether or not the variables were sent or not. Anybody know if send() is asynchronous?
If it is asynchronous, I guess I'd have to use sendAndLoad() in order to find out when the variables went through.
Loadmovie Asynchronous Problem?
I have a number of movies and I am using loadmovie commands to move from movie to movie. I am getting unpredictable results and have used traces to try sorting out the problem. The action script seems to be executing out of order. I'm guessing that this is due to the asynchronous nature of action script. I'm hoping for some suggestions on how to deal with this problem. Thanks much for your help!
Synchronous And Asynchronous Xml Loading?
I have a nested xml.onLoad within a function (with a return statement in the function)
I need to wait for the xml.onLoad to be triggered before a return statement is sent.
Flash does not wait for the xml to finish loading it will just return "undefined"; If you list variables in the debugger you will see that the object exists. Because it has had ample time to load. Has any one come across this issue and if so have you come up with a solution
[FMX04] OnLoad Is Asynchronous?
Are all onLoad() calls asynchronous?
For example, if you have 2 calls to a LoadVars.sendAndLoad(), is there any way to guarantee the arrival or the order in which the onLoad() routine is called?
I have a flash script in which I need one onLoad to be called before the other one... is there a way to do this?? or to make one wait to execute until after the other arrives?
Thanks all...
Asynchronous Loading Through Classes...
Hello,
Im trying to load up some images in actionscript, but i thought i would wrap it up in a class, and make a custom event for when it fires so all other classes can be notified. However theory and practiase rarely work out, and like i expected the event just seems to get lost somewhere...
Now just to simplify it ive got 2 classes...
imageLoader (static) and baseImage
now baseImage will call setupImage(file) which will call imageLoader.loadFile(file), this will then do its stuff then set an internal event event.COMPLETE, then this SHOULD fire an event event.IMAGE_LOADED that will be picked up by baseImage.imageLoaded(eventData:event).
However it looks like the event gets lost inside the class somehow...
Anyone had anything like this happen before as i cant seem to diagnose the problem...
Blocking On Asynchronous Calls
Hi,
I am loading XML data and want to stop my function returning until it has loaded. I came up with this:
ActionScript Code:
function Initialise():Boolean
{
var xmlVal:XML = new XML();
xmlVal.load("http://blah");
var bLoadedOK:Boolean = false;
var bFinished:Boolean = false;
xmlVal.onLoad = function (bSuccess)
{
bFinished = true;
bLoadedOK = bSuccess
}
while (!bFinished); //block until loaded
return bLoadedOK;
}
However, this doesn't work, because onLoad never gets called. It appears that xml.load() isn't truely asynchronous at all, and doesn't get called while my script is sitting in the loop.
So my question is, is there any way to do this? Or am I going to have to ugly global functions and variables everywhere to denote state changes?
True Asynchronous Communication?
I'm trying to figure out how to asynchronously communicate with a server. Flash seems to queue up all load/send/receive requests from LoadVars, XMLConnector and XML. I'm trying to stay clear from Flash remoting, too much of a hassle for what I want, but has anyone dealt with this before?
Asynchronous Flash Remoting W/J2EE?
I have been using flash remoting for some time, using the standard asynchronous (call, result function) architecture. Due to s restructuring of our service layer it would be exponentially beneficial if we were able to make synchronous calls to the webservice from flash.
Is there any way to make synchronous calls to the webservice from flash? Or possibly a third party extension that enables such capability?
So instead of:
J2EE.callFunction()
callFunction_Result = function(result)
{ var blah = result; }
you could just:
var blah = J2EE.callFunction();
How To Fix Asynchronous Communication Between Fscommand And Javascript
Hi all, I'm using fscommand to get a Value into Flash and modify it.
Everytime Flash doesn't recognize the value because
Flash doesn't wait and the value isn't filled at the modification process.
So i found a solution with Buttons, but i want to let this litlle demo-code (attached) run without Buttons.
Is there a way to insert a short pause or something like in java thread.sleep(xxx)?
Maybe it's also a problem with the SCORM-API (But that is not the point)
I hope you can help me,
Kind regards,
Darius
Attach Code
this.b1.onRelease=function(){
fscommand("LMSGetValue","cmi.suspend_data,returnval");
}
this.b2.onRelease=function(){
fscommand("LMSSetValue","cmi.suspend_data,"+returnval+"A");
}
this.b3.onRelease=function(){
fscommand("LMSCommit", "");
fscommand("CMISetCompleted", "");
fscommand("CMIFinish", "");
txtField.text=returnval;
}
Turning Asynchronous Calls To Synchronous
I did some research and I think I know the answer but I'll ask anyways hoping for some miracle.
Is there a way to have a synchronous call to a URL to retrieve the HTML code? If not, is it possible to turn an asynchronous call into a synchronous one using some trick? I can't believe Adobe wouldn't implement this option. I tried looping until the result is back but then the status function never fires making my loop infinite.
ranting.turn("ON");
I'm a ColdFusion developer and recently started working on a project in Flex. I am getting more and more frustrated with AS and Flex lately. It seems that whatever I'm trying to do is either really hard or impossible while it usually can be done with one line of code in ColdFusion. I'm still learning these languages and I'm sure my lack of knowledge is the reason but for some reason I can't get ahead with my project. It looks like the learning curve is much steeper than it should be. Maybe I just haven't found the right book/tutorial/site yet.
ranting.turn("OFF");
Anyways, here's my code for testing this functionality. The main application file looks like this:
Code:
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" applicationComplete="init()">
<mx:Script>
<![CDATA[
import myObjects.Domain;
public function init():void
{
var myDomain:Domain = new Domain();
trace("Final result: " + myDomain.testURL("http://test.com"));
}
]]>
</mx:Script>
</mx:WindowedApplication>
and the Domain object looks like this:
Code:
package myObjects
{
import flash.events.HTTPStatusEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class Domain
{
private var request:URLRequest;
private var responseCode:int = 0;
public function Domain()
{
}
public function testURL(url:String):Boolean
{
request = new URLRequest(url);
var loader:URLLoader;
loader = new URLLoader();
loader.load(request);
loader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, onStatus);
//while(responseCode == 0) {};
if(responseCode == 200)
{
return true;
}
else
{
return false;
}
}
private function onStatus(e:HTTPStatusEvent):void
{
if(e.status == 200 && url2Domain(e.responseURL) == url2Domain(request.url))
{
responseCode = 200;
trace("OK");
}
else if(e.status != 200)
{
responseCode = e.status;
trace("ERROR: Response code: " + e.status);
}
else
{
responseCode = 404;
trace("ERROR: Response for " + url2Domain(request.url) + " was returned from " + url2Domain(e.responseURL));
}
}
private function url2Domain(url:String):String
{
return url.toLowerCase().replace(new RegExp("^(https?://)?(www.)?"), "").split("/")[0];
}
}
}
This works OK except the function returns false before the HTTP call returns its result. If I un-comment the while loop the onStatus function will never be called and therefore end up with an infinite loop. Not sure why this happens.
Please let me know if you have any ideas on how to make synchronous calls or have a trick that waits for the result. Appreciate any help.
Synchronous/Asynchronous Loading Problem, Possibly?
I have a code that loads squares(individual SWF's) onto the Root movie, after the LoadSquares() function is called, i then call the MoveSquares() function, that moves the squares over next to eathother in a fixed width of 250. It moves the first square in the first spot, and if the width is still < than 250 then it would load the second square next to the first square, ETC, until the squares are > or = 250 then it would load the next square down to the next row, it would repeat the cycle until there are no more to load.
Sorry if this is a little confusing.
The problem is, whenever i do a regular test inside flash with CTRL+ENTER, it moves the maps perfectly, but whenever i try to 'simulate download' the move totally messes up. basically two of the squares' height's are set to 0, when it should be set at 100 or something(height is used to move the squares down a row). If i try to do a trace inside an onEnterFrame loop, i can grab the height only AFTER it defines it as 0. Can anyone try to help me with this problem? it's though, i have no clue where to go right now, been stuck on this for a couple days. Thanks!
Function Nesting Helps Against Asynchronous Calls?
Consider the following code
PHP Code:
public function callPHP(phpToCall:String):Boolean
{
var request:URLRequest = new URLRequest(phpToCall);
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, processData_Hdl);
try
{
loader.load(request);
}
catch(e:Error)
{
trace("Unable to load data.");
return false;
}
function processData_Hdl(e:Event):void
{
var loader:URLLoader = e.target as URLLoader;
if(loader.data.empty!="true")
{
/*php echo has to be like this: data=part1,,,part2,,,part3,,, etc*/
data = loader.data.data.split(",,,");
}
}
return true;
}
I often run into the problem that I want to get some data, call the function to get it, try to use the data, but the handler hasnīt done its work yet, thus ending up with errors. Before I run hundreds of tests, maybe somebody already knows a solution. For example when I nest the handler within the function making the data-retrieval would the "return true" help me to prevent asynchronous calls, as the statement comes after the declaration of the handler, thus when the handler has done its work? In the past I was so desperate that I used a bool and another enterframe handler to check whether data has arrived every frame. When it was set to true I had the green flag to use it. But there has to be a more elegant way, right?
The LoadVars.load Method Is An Asynchronous Action? Race Conditions?
I am trying to determine if a file exists on a server using the LoadVars.load method and checking for "success". I believe I am having an issue because I am actually using a 'for loop' to run through the file names while calling the '.load' method every iteration. However, every call seems to fork and do it's own thing while the loop continues.
This does actually work and it does find the file, but I don't want to make all these uneeded calls and more importantly...I am not even sure if there is a race condition and the variable I am depending on to be set further down in the code will be ready.
Is there any way to have my 'for loop' wait for the '.load' method to complete before continuing with the iterations? Maybe a while loop that checks '.isLoaded' or a more suitable method?
CODE:
PHP Code:
var vidExtensions:Array = new Array;
//These are all the possible movie file extensions that could be there
vidExtensions = [".3gp", ".3gp3", ".mpg", ".avi",
".mp4", ".mqv", ".mov"];
//Create the URL except the extension
var testPath:String = new String();
testPath = imgThumbPath.substr(0, imgThumbPath.indexOf("tn_"));
testPath += imgThumbPath.slice(testPath.length + 3, imgThumbPath.length - 4);
var fileExists = new LoadVars();
fileExists.onLoad=function(success)
{
if(success){
trace("SUCCESS!");
//We have found the correct file
myLink = unescape(""+sendPath);
}
else{
trace("FAIL");
}
}
//Loop through all possible movie extensions
for(var i=0;i<vidExtensions.length;i++){
var sendPath = testPath + vidExtensions[i];
//Check if file exists
fileExists.load(sendPath);
}
|