如何通过回调异步检索某些值来构建数组?

时间:2013-03-12 02:02:58

标签: javascript jquery asynchronous callback

我正在尝试构建一个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;
}

关于我应该如何处理的任何建议?

1 个答案:

答案 0 :(得分:0)

我推荐async flow control library。如果您了解它,您的复杂异步代码将变得更加干净和易于管理,并且不那么特别和牛仔编码。

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
});