Search code examples
javascripttitanium

Asyncronus function return


I'm working at an application in Titanium Studio. I have an MVC infrastructure implemented, and in a controller I want to get some data from the Cloud and only after that to call the view. The code is similar to this.

 Default : function() {
    Cloud.Objects.query({
        classname : 'Customer',
    }, function(e) {
            if (e.success) {
                Ti.API.info('aci ' + e.Customer);
                favorites = e.Customer;
                return this.view("Default", favorites);
            } else {
                alert('Error:\\n' + ((e.error && e.message) || JSON.stringify(e)));
            }
        });
    },
}

The thing is, that the first function has to return "this.view("Default", favorites);", not the callback from the query. Also, the query function is asyncronus and I have to wait for the data, and only then call the view.

Do you have any ideas?

Thank you


Solution

  • Create an even handler for some custom event like receiveCustomer.

    When customer retrieved, fire the event receiveCustomer and set customer as event data or initialize some variable outside the callback with retrieved data (but in this case before event triggering). In event hander onReceiveCustomer get the customer from the event data or from that variable and render the view.