开发者

Flex Async Madness - Any way to wait for a rpc.Responder to get a response before going to the next statement?

I feel like I must be doing this wrong. I've got a function that is supposed to construct a query based on an API's description of available fields. Here's what I've got:

var query_fields = getQueryFieldsFor(sobject_name);
// Need query fields for the next statement, which actually does the query

public function getQueryFieldsFor(sObject:String):String{
    //helper function to get queryfields for given sobject
    var queryFields:String = '';

    app.connection.describeS开发者_如何学CObject(sObject,
        new mx.rpc.Responder(
            function(result:DescribeSObjectResult):void{
                var returnFields:String = '';
                for ( var field:Field in result.fields ){
                    if(field.active){
                        returnFields.concat(field.name+',')
                    }
                }
             returnFields.slice(0, returnFields.length-1); //remove last comma
             queryFields = returnFields;
        }, function(error):void{
            Alert.show('error in getQueryFieldsFor function');
        })
     );

     return queryFields;
}

I know this doesn't work, and I think I understand why. However, I keep running into this type of issue and I believe I'm just thinking about it/designing it wrong. So what's a better pattern here? Would really appreciate any insight on this. Many thanks in advance.


It would be better to externalize your functions and execute your next line of code after the fact:

public function getQueryFieldsFor(sObject:String):String
{
    var responder:Responder = new Responder( onResult, onFault);
    app.connection.describeSObject(sObject, responder);
}

private function onResult(result:DescribeSObjectResult):void
{
        var returnFields:String = '';
        for ( var field:Field in result.fields ){
            if(field.active){
                returnFields.concat(field.name+',')
            }
        }
     returnFields.slice(0, returnFields.length-1); //remove last comma
     queryFields = returnFields;
}

Your main problem though is not the code, but a lack of thinking asynchronously. You cannot have a function called "getQueryFields" that will return it instantly. What you want to do is think in the request/response way. You're trying to get some data, a request is made to a service, gets the data back, updates a property which is then binded to a view which gets redrawn. This is the proper way to do any webapp.

It might be beneficial for you to also look at application frameworks like RobotLegs and Parsley since it helps you manage these situations. Parsley also has a task library which lets you perform several asynchronous task one after another.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜