繁体   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