在自己内部嵌套回调

时间:2015-01-27 21:28:05

标签: javascript callback

我认为我正在寻找嵌套回调,但我真的不确定要使用的术语或编程方法。

我遇到的问题是我编程时使用Google Places API获取特定搜索的所有结果。

我无法知道自己会有多少结果,所以如果某个对象属性存在且我从Google收到回复,我将需要循环回调

据我所知,我需要检查是否存在其他页面,如果存在,请再次运行回调,但我不确定将该呼叫放在哪里。 它绝对是同步的因为我必须等待响应以确定是否再次运行。

这是我迄今为止所做的尝试:

function secondCallback(error, response, body) {
    console.log(JSON.parse(body));
}

function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        var results = JSON.parse(body);
        var page_token = results.next_page_token;

        if (page_token) {
            console.log(results);
            console.log('there is another token to run');
            options.url += '&pagetoken='+page_token;
            console.log('with this token:' + options.url);
            request(options, callback); // doesn't work
            callback(); // doesn't work
        } else {
            console.log(results);
            console.log('no more results');
        }
    }
}

request(options, callback);

假设我可以进行几乎无限次的迭代,那么做这样的事情最简洁的方法是什么?

我的控制台看起来像这样:

...
{ geometry: [Object],
   icon: 'http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png',
   opening_hours: [Object],
   photos: [Object],
   scope: 'GOOGLE',
   types: [Object],
  status: 'OK' }
there is another token to run
with this token:https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=API_KEY&location=39.0997265,-94.57856670000001&radius=16093.4&keyword=guitar&pagetoken=CoQC9AAAAD8nKIOlABe_PU7NIaHP8320A7oY1avuGKYlpPMhba6HYwQmAhLvaGXPcPOlWK-V4VafGJLTUAmhplf7bvHv__fHSWSkkwvVpBzljntB9hMQIxoUnwZAyi3jU5Cyw2WQ_fZ3AJzLMO9ti_uv_Z2RAnAW694EDMDlyrONRKY3Yjrx0Ri9dJrzP0PWY2AtVJFqsLSquPb8azSnS3gINuCLe-Y5-Q18vq__V6pEuUNSipf_Trww1cGH67Q6oZ0aa6CAmrp8YSOJ7St6O1tmbj_N0gjBuNpqZ-k_YAhL3zeVYNIX8IWC3KHkVZkFAXSlN0RaV0Yd_K0gHpKeJmGLVjH5zlgSEAMR_J112AV2lAC7afssRPYaFFvW3fiySrpMQCsIsGpFSyWvulxm
{ html_attributions: [], results: [], status: 'INVALID_REQUEST' }
no more results

快速搜索Google地方信息API会显示状态响应:INVALID_REQUEST generally indicates that a required query parameter (location or radius) is missing.但我确认我只是发送了修改了&pagetoken=PAGE_TOKEN的请求网址。< / p>

我已将它隔离到这些行(请参阅第一个代码粘贴):

request('https://maps.googleapis.com/maps/api/place/nearbysearch/json?key='+apiKey+'&location='+latLong+'&radius='+radius+'&pagetoken=CoQC9AAAALHMvGfCqSR3TvplrBKu6Ra7YQXS1TpteDN0Cd_9HuyGUa1v7lFbFdCkezzqtG02CKBAkYpp1_VgOtz6Eu6ivKtsEsKNiHGj2KBvdI7tTZVxz-LZES8nZmcu-dFlDSKYYKVhD00sD26zAASvTGfdZ31wX62DesBxeI6TyPP3Zh6I_IW3W2yvUNZJ0hUNyZX-6t03YEDwacUw7oUL_gueOlkIIB93C4X0-zRyBFjzFUmAtzu45MXjINQ9RwHwlZnLqBqeKEhuWaTXBpxfkE1dQuuH4fIqBI-Ytnj_dDq4J1xhNav1Qk0BYo59PPqFVquWRI_KrJzm5fo11n4SeqAj_-4SEGMXaSFnDegQ5zWI-7qip4waFBj6NGnjVeXIjxTo3KpN4EdmigEa', secondCallback); // works
        console.log(pageToken); // is what it should be
        request('https://maps.googleapis.com/maps/api/place/nearbysearch/json?key='+apiKey+'&location='+latLong+'&radius='+radius+'&pagetoken='+pageToken, secondCallback); // seems to be a proper string

1 个答案:

答案 0 :(得分:1)

这是一个使用jQuery的简单示例,如果我们的数据具有next_page_url属性,那么在每次Ajax成功时我们都会进行另一次Ajax调用。

function out(str) {
  $(document.createElement('h2'))
    .text(str)
    .appendTo(document.body);
}

function error(err, errText) {
  console.log('ERROR: ', errText);
}

function success(data) {
  if (data) {
    if(data.next_page_url) {
      // Make another request if our data has another URL
      request(data.next_page_url);
    }

    out(data.title);
  }
}

function request(url) {
  return $.ajax({
    url: url,
    dataType: 'json'
  })
  .done(success)
  .fail(error);
}

request('http://jsbin.com/fohozupaqi/1.json');

我们要求的网址是:

以下是一个实例:http://jsbin.com/cecafiqexo/1/edit?html,js,output

我希望它有所帮助!