AS3 - 如何做一个异步调用的同步负荷?负荷、如何做一个

2023-09-09 21:34:44 作者:20.键盘感情

我有一个函数加载用户对象从一个Web服务是异步的。

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.

例如:

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

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

            return newUser;
        }

UserFactory.GetCurrent看起来是这样的:

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??

你如何完成这一类型的返回功能的Flex的?

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

推荐答案

这是疯狂的。

说真的,你最好不要试图强迫异步调用变成某种同步架构。学习对你有利的事件处理系统的工作原理,并添加一个处理结果的事件。事实上,这里的建议直接从柔性codeRS 常见问题:

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.