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 に答える