2015-10-06 37 views
0

我很难理解如何在Fb.api调用之外设置一个变量,该变量位于该调用的回调函数内部。变量photoid被设置在for循环内,然后在那个for循环里面,我用那个改变photoid来做一个FB.api调用。 (我甚至使用photoid构建电话,你会看到)。这部分工作都很好,但我在控制台中注意到photoid没有传递到该回调函数中,因此我试图保存与先前设置的变量(taggedpersonid = specialfriendvar)相匹配的所有photoid。在Fb.api回调内拉外部变量

我相信这个解决方案与闭包(或许)有关,但我不太了解它们,并希望得到一些帮助。我怎样才能得到我的回调函数中的每个photoid变量,以便它将成功保存到我的photosbasket数组中,如果匹配成立?

function proceedToResult() { 
 
    FB.api('/me', function(response) { 
 
    var fbid = response.id; 
 
    var profile_name_beta = response.name; 
 
    console.log(profile_name_beta); 
 
    FB.api('/me/photos', { 
 
     fields: ['id'], 
 
     limit: 200 
 
     }, 
 
     function(response) { 
 
     console.log(response); 
 
     if (response && !response.error) { 
 
      if (response.data.length > 0) { 
 
      for (var i = 0; i < response.data.length; i++) { 
 
       var photoid = response.data[i].id; 
 
       console.log(photoid); 
 
       FB.api('' + photoid + '/tags', function(response) { 
 
       console.log(response); 
 
       console.log("inside photoid is" + photoid); 
 
       for (var l = 0; l < response.data.length; l++) { 
 
        var taggedpersonid = response.data[l].id; 
 
        if (taggedpersonid == specialfriendvar) { // if photo has tagged same as chosen friend 
 
        photosbasket.push(photoid); 
 
        console.log(photosbasket); 
 
        } 
 
       } 
 
       }); 
 
      } 
 
      } 
 
     } 
 
     } 
 
    ); 
 

 
    }); 
 
}

+0

你可以简单的让你的要求'/photo-id?fields = id,tags代替 - 那么API也会返回id,并且您可以将其作为响应的一部分进行访问。 – CBroe

回答

0

,您可以创建另一个函数,这将范围变量该功能,使您的代码更易读:

function proceedToResult() { 
    FB.api('/me', function(response) { 
     var fbid = response.id; 
     var profile_name_beta = response.name; 
     console.log(profile_name_beta); 
     FB.api('/me/photos', { 
       fields: ['id'], 
       limit: 200 
      }, 
      function(response) { 
       console.log(response); 
       if (response && !response.error) { 
        if (response.data.length > 0) { 
         for (var i = 0; i < response.data.length; i++) { 
          var photoid = response.data[i].id; 
          console.log(photoid); 
          getPhoto(photoid); 
         } 
        } 
       } 
      } 
     ); 

    }); 
} 

function getPhoto(photoid) { 
    FB.api('' + photoid + '/tags', function(response) { 
     console.log(response); 
     console.log("inside photoid is" + photoid); 
     for (var l = 0; l < response.data.length; l++) { 
      var taggedpersonid = response.data[l].id; 
      if (taggedpersonid == specialfriendvar) { // if photo has tagged same as chosen friend 
       photosbasket.push(photoid); 
       console.log(photosbasket); 
      } 
     } 
    }); 
}