簡體   English   中英

如何在javascript中實現同步行為?

[英]How can I achieve synchronous like behaviour in javascript?

    var routeSearch = new MyGlobal.findRoutes({
        originPlaceId: search.placeInputIds.originPlaceId,
        destinationPlaceId: search.placeInputIds.destinationPlaceId,
        directionsService: search.directionsService,
        directionsDisplay: search.directionsDisplay,
        travel_mode: search.travel_mode
    });

    var routeBoxes = new MyGlobal.routeBoxes({
        radius: parseFloat(document.getElementById("radius").value),
        path: routeSearch.grabFirstRoute(),
        map: search.map
    });

$(document).on('ready', function(){
    MyGlobal.findRoutes = function(request){
        var me = this;
        this.response;
        this.grabFirstRoute = function(){
            return this.response.routes[0].overview_path; // first route from directions service response
        };

        if (!request.originPlaceId || !request.destinationPlaceId) {
            return;
        }
        request.directionsService.route({
            origin: {'placeId': request.originPlaceId},
            destination: {'placeId': request.destinationPlaceId},
            travelMode: request.travel_mode
        }, function(response, status){
            if (status === google.maps.DirectionsStatus.OK) {
                me.response = response;
                request.directionsDisplay.setDirections(response);

            } else {
                window.alert('Directions request failed due to ' + status);
            }
        });
    }
})

我不知道如何解決這個問題。 在轉到MyGlobal.routeBoxes構造函數之前,MyGlobal.findRoutes構造函數不會等待響應從directionsService返回。 是否有一種簡單的方法來設置我的代碼,以便MyGlobal.findRoutes構造函數內的所有進程在繼續之前完成?

您可能希望使用某種形式的“承諾”來增加語法的好處並使您的代碼更容易推理。 但是,堅持你發布的代碼,你可以使用回調(在較大的應用程序中可能會變得很麻煩)來實現類似的東西。 展示:

var routeBoxes;

function bootstrapRouteBoxes() {
    routeBoxes = new MyGlobal.routeBoxes({
        // code shortened
    });
}

var routeSearch = new MyGlobal.findRoutes({
    // code shortened
}, function() { bootstrapRouteBoxes(); }); // <-- callback as second arg added

然后允許你的findRoutes函數來處理該回調:

MyGlobal.findRoutes = function(request, callback){
    // code shortened

    request.directionsService.route({
        // code shortened
    }, function(response, status){
        if (status === google.maps.DirectionsStatus.OK) {
            me.response = response;
            request.directionsDisplay.setDirections(response);
            callback(); // <-- new code
        } else {
            window.alert('Directions request failed due to ' + status);
        }
    });
}

不會使事情同步,這是一件好事,因為否則你的應用可能會在獲取數據時“凍結”。 確保您routeBoxes並不構成直到其他服務已成功返回並調用callback


作為腳注,對於承諾,您可以使用各種選項。 也許不是最好的,但是接近你已經使用的libs: jQuery承諾 如果您正在使用Angular,您還可以查看$q文檔 但這是一個廣泛的主題,並不一定與您的問題直接相關。 調查,如果您有特定問題,請回到SO。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM