Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

apache flex - AS3 - How to do a synchronous load of an asynchronous call?

I have a function that loads a user object from a web service asynchronously.

I wrap this function call in another function and make it synchronous.

For example:

    private function getUser():User{
            var newUser:User;
            var f:UserFactory = new UserFactory();

            f.GetCurrent(function(u:User):void{
                newUser = u;
            });

            return newUser;
        }

UserFactory.GetCurrent looks like this:

public function GetCurrent(callback:Function):void{ }

But my understanding is there is no guarantee that when this function gets called, newUser will actually be the new user??

How do you accomplish this type of return function in Flex?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This way madness lies.

Seriously, you're better off not trying to force an asynchronous call into some kind of synchronous architecture. Learn how the event handling system works in your favour and add a handler for the result event. In fact, here's the advice straight from the flexcoders FAQ :

Q: How do I make synchronous data calls?

A: You CANNOT do synchronous calls. You MUST use the result event. No,
you can't use a loop, or setInterval or even callLater.  This paradigm is
quite aggravating at first. Take a deep breath, surrender to the
inevitable, resistance is futile.

There is a generic way to handle the asynchronous nature of data service
calls called ACT (Asynchronous Call Token). Search for this in
Developing Flex Apps doc for a full description.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...