开发者

jQuery deferred not working for me?

I'm trying to use the jQuery when function, in order to wait until an Ajax request completes before proceeding onwards, but am clearly getting something wrong.

My console output looks like this:

geocodeMaster
geocode Canary Wharf 
Object
geocode  
Object
address is blank, returning 51.501885 -0.190894
proceeding
Uncaught TypeError: Cannot read property '0' of undefined
Object
Object

The final two Objects are the output from the second call to geocode. Why does the code show proceeding before the output of the second call?

My code looks like this:

function geocode(address, geodata) {
    console.log('geocode', address, geodata);
    geodata['street'] = address;
    if (address=="") {
        console.log('address is blank, returning ' + current_latlng[0], current_latlng[1]);
        return [current_latlng[0], current_latlng[1]];  
    }
    $.ajax({
        url: CS_API + 'geocoder.json',
        data: geodata,
        dataType: 'jsonp',
        jsonpCallback:开发者_StackOverflow 'places',
        success: function(from_data) {
            console.log(from_data);
            if (from_data.results.result!=undefined){
               var from_result = from_data.results.result;
               console.log(from_result)
               return [from_result.latitude, from_result.longitude];   
            } else {
                return false;
            }
        },
        error: function(data) {
            return false;
        }   
    }); 
}
function geocodeMaster(place_from,place_to) {
    console.log('geocodeMaster');
    geodata['key'] = CS_API_KEY;
    if (current_latlng!=null) {
        geodata['n'] = current_latlng[0] + 0.1;
        geodata['e'] = current_latlng[1] + 0.1;
        geodata['s'] = current_latlng[0] - 0.1;
        geodata['w'] = current_latlng[1] - 0.1;
    }
    var start_coords,finish_coords;
    $.when(start_coords=geocode(place_from,geodata),finish_coords=geocode(place_to,geodata)).then(function(){
console.log('proceeding');
        console.log(start_coords[0],start_coords[1],finish_coords[0],finish_coords[1]);  
    });      
}

Is the problem that the objects supplied to when() are not Deferred objects? If so, how can I make them into Deferred objects, while keeping the information that I need to collect - start_lat, etc?


You must return a deferred object from the geocode function. Try :

return $.ajax(..

You cannot store the return value directly into values (it does not work the way it's written now). You have to store them somewhere else, so that the line that calls the when simply reads :

$.when(geocode(place_from,geodata),geocode(....

To solve this, you could pass to geocode an empty object, and have that function save its result in it, for example :

var start_coords = {};
var finish_coords = {};
$.when(geocode(place_from,geodata,start_coords),geocode(place_to,geodata,finish_coords) ... 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜