简体   繁体   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);
            }
        });
    }
})

I'm not sure how to solve this problem. 我不知道如何解决这个问题。 The MyGlobal.findRoutes constructor doesn't wait for the response to come back from the directionsService before moving on to the MyGlobal.routeBoxes constructor. 在转到MyGlobal.routeBoxes构造函数之前,MyGlobal.findRoutes构造函数不会等待响应从directionsService返回。 Is there an easy way to set up my code so that all processes inside of the MyGlobal.findRoutes constructor finish before moving on? 是否有一种简单的方法来设置我的代码,以便MyGlobal.findRoutes构造函数内的所有进程在继续之前完成?

You probably want to use some form of "promises" that add syntactic niceness and make your code easier to reason about. 您可能希望使用某种形式的“承诺”来增加语法的好处并使您的代码更容易推理。 But, sticking to the code you've posted, you can use callbacks (which can become cumbersome in larger apps) to achieve something similar. 但是,坚持你发布的代码,你可以使用回调(在较大的应用程序中可能会变得很麻烦)来实现类似的东西。 To demonstrate: 展示:

var routeBoxes;

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

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

And then allow your findRoutes function to handle that callback: 然后允许你的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);
        }
    });
}

This will not make things synchronous, which is a good thing because otherwise your app might "freeze" while fetching data. 不会使事情同步,这是一件好事,因为否则你的应用可能会在获取数据时“冻结”。 It will make sure your routeBoxes aren't constructed until the other service has successfully returned and calls the callback . 确保您routeBoxes并不构成直到其他服务已成功返回并调用callback


As a footnote, for promises you can use various options. 作为脚注,对于承诺,您可以使用各种选项。 Perhaps not the best, but one that's close to what libs you already seem to be using: jQuery promises . 也许不是最好的,但是接近你已经使用的libs: jQuery承诺 If you're using Angular you can also have a look at the $q documentation . 如果您正在使用Angular,您还可以查看$q文档 But it's a broad topic, and not necessarily directly related to your question. 但这是一个广泛的主题,并不一定与您的问题直接相关。 Investigate, and get back to SO if you have a specific question. 调查,如果您有特定问题,请回到SO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我们如何在需要时保证 Javascript 中的同步行为? - How we can guarantee synchronous behaviour in Javascript when we need it? Javascript:如何进行同步循环? - Javascript: How can I make Synchronous Loop? 如何使用Javascript / Jquery实现这些? - How can i achieve the these with Javascript / Jquery? 如何在 JavaScript 中实现点击事件? - How can I achieve click event in JavaScript? 我想用 api 中的一个替换我的本地阵列,同时在 javascript 中保持相同的功能。 我怎样才能做到这一点? - I would like to replace my local array with one from an api whilst keeping the same functionality in javascript. How can I achieve this? 如何在类似街机的游戏中实现环绕效果? - How can I achieve a wraparound effect in an arcade-like game? 如何测量 JavaScript 中的同步 http 请求所花费的时间? - How can I measure time taken by a synchronous http request in JavaScript? 如何在javascript中模拟生成器的同步调用? - How can I emulate a synchronous call with generators in javascript? 如何实现hover效果? 具有 hover 的一个元素对另一个行为有影响吗? - How can I achieve hover effect? One element with hover influence on behaviour another? 不支持超时时如何实现javascript同步xmlhttprequest? - How can I achieve javascript sync xmlhttprequest with timeout when it is not supported?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM