简体   繁体   中英

Where I should place return statement

I use Backbone.js and jQuery 1.7 in my application and I have some problems in building collection. In collection I have the method, which should return some object. I do "return" in $.ajax(...) success() function.

In this case i receive "undefined" instead of expected object. I understand, that the problem is in the "return" - it make success() function return some value. But I need getDomainZones() method do a return. How can I do it?

window.DmnList = Backbone.Collection.extend({
        model: DmnItem,
        localStorage: new Store("hosting.WhoIs"),
        destroyAll: function (options) {
            while (this.models.length > 0) {
                this.models[0].destroy(options);
            }
        },
        getDomainZones: function(){
            $.ajax({
                url: 'http://hosting/rest/getDomains',
                type: 'GET',
                dataType: 'json',
                cache: 'false',
                timeout: 5000,
                success: function(data) {
                    console.log(data);
                    return data;//problem here
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log("Error[getDomainZones]: " + textStatus);
                    console.log(jqXHR);
                },
            });
        }
});

" Where I should place return statement"

Nowhere. You can't return the result of an asynchronous AJAX request.

Any code that relies on the data , must be called inside the success callback.


One possibility is to have your getDomainZones method receive a function that will be called when the response is received.

getDomainZones: function( callback ){
    $.ajax({
        url: 'http://hosting/rest/getDomains',
        type: 'GET',
        dataType: 'json',
        cache: 'false',
        timeout: 5000,

   //   success: callback,  // alternative if there's no other work to do.
        success: function(data) {
            console.log(data);

            callback( data ); // invoke the function received
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("Error[getDomainZones]: " + textStatus);
            console.log(jqXHR);
        },
    });
}

So then you'd pass a function to getDomainZones , and when the response is received, getDomainZones will invoke the function you passed, passing it the data .

getDomainZones( function( d ) {
    // do something with the data
    console.log( d );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM