简体   繁体   English

从Javascript中的回调函数返回

[英]Return from a callback function in Javascript

I am new to Javascript coding and have looked for this information in many places but haven't found one working solution, hence I am posting this question here. 我是Javascript编码的新手,并且已经在很多地方寻找这些信息,但是没有找到一个有用的解决方案,因此我在这里发布这个问题。

In a for loop I am trying to request POIs in a region (leg of the route) using - 在for循环中,我试图在一个区域(路线的一条腿)中使用以下方式请求POI:

service.search(request, callback);

where request includes parameters like location and type of POI queried. 其中request包括查询的POI的位置和类型等参数。 I have implemented the callback function as below - 我已经实现了如下的回调函数 -

function callback(myResults, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        alert('myResults: ' + myResults.length);
        // entire remaining code here, where I do some processing on the POIs.
    }   
}

This code is working and at each leg of the route I get to see the POIs, and also number of POIs is displayed using alert. 这段代码正常运行,在路线的每一段我都可以看到POI,并且还会使用alert显示POI的数量。

My issue is that I do not want to process the "myResult" here for each leg, but collect all the results for the entire route (made up of many legs) and then do the processing at once. 我的问题是我不想在这里为每条腿处理“myResult”,而是收集整条路线的所有结果(由许多腿组成),然后立即进行处理。

  1. I first thought of creating a global variable ("myPOIs") and append "myResults" at each leg and once the entire route is parsed, then to process this myPOIs, but I am not able (or I dont know how) to append this myResults to a global variable myPOIs. 我首先考虑创建一个全局变量(“myPOIs”)并在每条腿上追加“myResults”,一旦整个路径被解析,然后处理这个myPOI,但我无法(或者我不知道如何)追加这个myResults到一个全局变量myPOIs。

  2. The other option, I was thinking of is getting a return (myResults) from the callback function and then collecting (appending) all the results. 我想到的另一个选择是从回调函数获得一个return(myResults),然后收集(追加)所有结果。

The only difference between 1 and 2 is that, in 1, its a global variable I will be appending myResults to within the if condition, and in 2, if the if condition is true then return the myResults to the service.search and then collect the results there. 1和2之间的唯一区别在于,在1中,它是一个全局变量,我将myResults附加到if条件中,在2中,如果if条件为true,则将myResults返回到service.search然后收集那里的结果。

I tried using myPOIs.push(myResults) and a few other options, but when I check the myPOIs.length it is always null. 我尝试使用myPOIs.push(myResults)和其他一些选项,但是当我检查myPOIs.length时,它总是为空。 I really dont know how to get the myResults out of the callback function. 我真的不知道如何让myResults退出回调函数。

Any suggestion/ throughts/ help will be very useful for me. 任何建议/通过/帮助对我都非常有用。

And I want to use only javascript and nothing else for this. 我想只使用javascript,而不是其他。

Thanks a lot in advance, axs 非常感谢,斧头

Assuming you are calling the search something like this: 假设你正在调用这样的搜索:

for (var i = 0; i < legs.length; i++) {
    service.search(legs[i], callback);
}

then you can do this by keeping track of all the results, and the number of times you've been called back: 那么你可以通过跟踪所有结果以及你被回叫的次数来做到这一点:

var callbacksOutstanding = legs.length;
var allPlaces = [];
var callback = function(legPlaces, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        allPlaces.push.apply(allPlaces, legPlaces);
    } 
    if (--callbacksOustanding === 0) {
        processPlaces(allPlaces);
    }
};
for (var i = 0; i < legs.length; i++) {
    service.search(legs[i], callback);
}

Where processPlaces is some function you've written to process the complete array of PlaceResult objects. processPlaces是您编写的一些函数,用于处理PlaceResult对象的完整数组。

Now the three var statements there are not global variables if this is all wrapped in a function (as it should be), because in Javascript you can and should define functions inside other functions. 现在三个var语句没有全局变量,如果它全部包含在一个函数中(因为它应该是),因为在Javascript中你可以而且应该在其他函数中定义函数。 And if you do so, the inner functions will have access to variables in the outer functions. 如果这样做,内部函数将可以访问外部函数中的变量。 So for me this might look like this: 所以对我来说这可能是这样的:

function findAndProcessPlaces(legs) {
    var callbacksOutstanding = legs.length;
    var allPlaces = [];
    var callback = function(legPlaces, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            allPlaces.push.apply(allPlaces, legPlaces);
        } 
        if (--callbacksOustanding === 0) {
            processPlaces(allPlaces);
        }
    };
    for (var i = 0; i < legs.length; i++) {
        service.search(legs[i], callback);
    }
}

NB: The allPlaces.push.apply line performs an in-place concatenation of one array to another. 注意: allPlaces.push.apply行执行一个数组到另一个数组的就地连接。 You could also write: 你也可以这样写:

allPlaces = allPlaces.concat(legPlaces)

at this point. 这一点。

Make a global variable: 创建一个全局变量:

var POIResults = [];

In your function callback 在你的函数回调中

POIResults.push(myResults);

Later at your convenience, call a function which iterates the array 稍后在方便的时候,调用一个迭代数组的函数

function checkResults(){
 for(var i = 0; i < POIResults.length; i++){
  //TODO: check POIResults[i]
 }
} 

An array defined out side the call back and within theright scope should do the trick. 在回调范围内定义的一个数组应该可以解决问题。 Can you post the code with the global array approach? 你能用全局数组方法发布代码吗?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM