在自身内嵌套回调

Nesting Callbacks Within Themselves

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

我遇到的问题是当我编写一种方法来获取特定搜索的所有结果时 Google Places API.

我无法知道我会得到多少结果,所以如果某个对象 属性 存在我从 [=37 返回的响应,我将需要循环回调=].

据我所知,我需要检查是否存在另一个页面,如果存在,运行 再次回调,但我不确定该调用的位置。 肯定是同步的,因为我必须等待响应才能确定是否再次运行。

这是我到目前为止尝试过的方法:

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. 但是我正在验证我只是发送请求 url &pagetoken=PAGE_TOKEN修改为它。

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

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

这是一个使用 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');

我们请求的 URL 是:

这是一个活生生的例子:http://jsbin.com/cecafiqexo/1/edit?html,js,output

希望对您有所帮助!