0

我正在尝试构建一个 JavaScript 函数,该函数将根据一些用户输入返回一个目的地数组。一些输入可以直接放入数组中(例如当用户输入地址时)。其他时候,我需要使用 Google Places API 将地点(即五金店)翻译成现实世界的目的地。问题是这些目的地是通过回调异步返回的。当我有这些位置通过回调在所有不同时间进入时,如何建立然后使用数组?

这是我到目前为止的代码:

function parseDestinations(){
    var listItems = $('#InputBoxesList').children();
    var destinations = [];
    for(var i=0; i< listItems.length;i++){
        var selector = $(listItems[i]).children('.locationTypeSelector')[0];
        var locationInputBox = $(listItems[i]).children('.locationInput')[0];
        var selectedValue = selector.options[selector.selectedIndex].value.replace('select_','');

        if(selectedValue == selectTypes.Address.value){
            destinations.push({
                location: locationInputBox.value,
                stopover: true
            });
            calcRouteFromCurrentLocation(destinations);
        }
        else if(selectedValue == selectTypes.GenericLocation.value){
            var type = [];
            type.push(locationInputBox.value);
            var request = {
                location: currentLocation,
                types: type,
                rankBy: google.maps.places.RankBy.DISTANCE 
            };
            placesService.nearbySearch(request, function(results, status){

                //I don't know what to do here...

            });
        }
        else if(selectedValue == selectTypes.Chain.value){
            alert('Searching by Chain not supported yet');
        }
        else if(selectedValue == selectTypes.Item.value){
            alert('Searching by Item not supported yet');
        }

    }
    return destinations;
}

关于我应该如何处理这个问题的任何建议?

4

1 回答 1

0

我推荐异步流控制库。如果你学会了它,你复杂的异步代码将变得更加干净和易于管理,并且更少的临时和牛仔编码。

async.parallel(destinations, function (destination, callback) {
    //if need an async call, do
    lookupDestination(destination, function (result) {
        //tell async this one is done
        callback(null, result);
    });
    //otherwise if you don't need a async call, just
    return callback(null, lookupSync(destination));
}, function (error, done) {
    //now `done` is a list of resolved destinations
    //go to town
});
于 2013-03-12T02:24:33.237 回答