JavaScript - 回调 - 等待多个函数结束 [英] JavaScript - callback - waiting for multiple functions to end

查看:284
本文介绍了JavaScript - 回调 - 等待多个函数结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用google maps api从许多不同的起点计算到目的地点的最短路径。我决定这样做:(计数每一对点,而不是保存结果到数组,而不是检查在结束,这是最好的)。但我有回调的问题 - 因为作为注释说,数组总是零 - 因为这个代码是在所有请求计数路由长度之前执行。

I count the shortest path to the destination point from many different origin points with google maps api. I decided to do it this way : (count for each pair of points than save results to array and than check at the end which is best). But i have problem with callback - because as comments says array is always zero - because this code is performed before all requests to count the route length.

function foo(){
var directionsService = new google.maps.DirectionsService();
var destination = new google.maps.LatLng(x,y);
var arrayOfRes= [];

for(var index in originPoints){
    var request = {
        origin:originPoints[index].marker.position,
        destination:destination,
        travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                var res = {};
                res.length = result.routes[0].legs[0].distance.value;
                res.index = index;
                res.result = result;
                arrayOfRes.push(res);
            }
     });
}
  //here arrayOfRes.length is always 0
if(arrayOfRes.length>1)
{
    var bestResult = arrayOfRes[0];

    for(var i = 1; i < arrayOfRes.length; i++)
    {
        if(bestResult.length > arrayOfRes[i])
            bestResult = arrayOfRes[i];
    }

    console.log("Best is" + bestResult.length);
}
else if(arrayOfRes.length ==1)
{
    var bestResult = arrayOfRes[0];
}
 }

如何使用回调函数编写函数,所有请求都会结束?

How to write function with callback so that it wait until all requessts are ended?

推荐答案

这样的Google请求是异步的,因此您必须编写异步代码,数据从回调。

Google requests like this are asynchronous so you have to write asynchronous code which means ONLY working with the returned data from the callback.

在回传路径的回调函数中,您需要检查这是否是最后一个请求的答案。

In your callback function that returns a route, you need to check if this is the answer to the last request. If so, then your array has all the results and you can then process the array.

假设 originPoints 是所有的结果,一个数组,你可以这样做:

Assuming that originPoints is an array, you could do it like this:

var arrayOfRes = [];
for (var index = 0; index < originPoints.length; ++index) {
    var request = {
        origin:originPoints[index].marker.position,
        destination:destination,
        travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            var res = {};
            res.length = result.routes[0].legs[0].distance.value;
            res.index = index;
            res.result = result;
            arrayOfRes.push(res);

            // check if all data has arrived
            if (arrayOfRes.length === originPoints.length) {
                // put code here to process arrayOfRes
            }
        }
    });
}



注意:javascript不能让你的代码等待所有请求完成然后继续 - 因此你必须使用异步编程风格与从回调继续的代码流。

Note: javascript does not have the ability to make your code wait for all the requests to be done and then continue - thus you have to use an asynchronous programming style with the flow of code continuing from the callback.

注意:因为 directionsService.route 是一个异步调用,它将来在某个时候调用它的回调。在此期间,你的JS将继续执行。这意味着,紧接着这段代码之后的代码将在ajax调用完成之前和填充 arrayOfRes 之前执行。因此,您可以安全地使用 arrayOfRes 数据的唯一位置是回调本身或您从回调中调用的函数。

Note: because directionsService.route is an asynchronous call, it will call its callback sometime in the future. In the meantime, you JS will continue to execute. That means that the code that comes right after this block of code will execute BEFORE the ajax calls have completed and before arrayOfRes is populated. As such, the ONLY place you can safely use the arrayOfRes data is in the callback itself or in a function that you call from the callback.

这篇关于JavaScript - 回调 - 等待多个函数结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆