2011-09-06 53 views
0

我有一個Facebook API的問題。我可能不會採用這種最好的方式,但這裏是我所擁有的。迴應的Facebook API回調

我有一個request_ids數組,我需要將其轉換爲用戶ID。 我有一個while循環查詢請求ID並獲取用戶ID。

function (response) { 
    var requestsToSend = new Array(); 
    var i = 0; 

    while (i < response.request_ids.length) 
    { 
     FB.api('/'+response.request_ids[i], function(res){ 
      requestsToSend[i] = res['to']['id']; 
     }); 
     i++; 
    } 
    console.log(requestsToSend[0], requestsToSend[1], requestsToSend[2], requestsToSend[3]); 
} 

這工作正常。但是,當我回顯返回的id(console.log)時,它們未定義,因爲FB.api尚未返回值/響應。

只有在FB.api返回值時,纔有辦法觸發console.log? 我真的不想設置一個定時器來觸發該功能。

+0

我認爲水庫是一個對象,你使用的資源作爲一個數組。 – munjal

+0

res是一個json對象 – atmd

回答

0

㈣固定的問題,但不是非常滿意的解決方案

function (response) { 

      var requestsToSend = new Array(); 
      var i = 0; 
      var arry = new Array(); 


         FB.api('/'+response.request_ids[0], function(res){ 
          if(typeof res['to'] != 'undefined'){ 
           useResults(res['to']['id']); 
          } 
         }); 

         FB.api('/'+response.request_ids[1], function(res){ 
          if(typeof res['to'] != 'undefined'){ 
           useResults(res['to']['id']); 
          } 
         }); 

         FB.api('/'+response.request_ids[2], function(res){ 
          if(typeof res['to'] != 'undefined'){ 
           useResults(res['to']['id']); 
          } 
         }); 

         FB.api('/'+response.request_ids[3], function(res){ 
          if(typeof res['to'] != 'undefined'){     
           useResults(res['to']['id']); 
          } 
         }); 

       function useResults(value){ 
        arry.push(value); 
        timeToFire(arry); 
       } 

       function timeToFire(arry){ 

        if(arry.length == response.request_ids.length){ 
         //console.log(arry); 
         playTheGame(arry[0], arry[1], arry[2], arry[3]); 
        } 
       } 
     } 
0

把你的console.log呼叫響應函數:

function (response) { 
    var requestsToSend = new Array(); 
    var i = 0; 
    while(i < response.request_ids.length) { 
     FB.api('/'+response.request_ids[i], function(res){ 
      requestsToSend[i] = res['to']['id']; 
      console.log(requestsToSend[i]); 
     }); 
     i++; 
    }  
} 
+0

我知道你的建議有效,但它不幫助我。我知道什麼是返回的值,但我需要使用它們,一旦它們都返回 – atmd

+0

所以首先定義一個數組來存儲它們,如: var finalRequests = [] 然後替換控制檯。在我的例子中的日誌代碼: finalRequests.push(requestsToSend [i]) 當代碼退出while循環的底部時,您將有一系列請求可供使用。 – slashwhatever