2012-02-09 60 views
0

我正面临着在for循环中运行FB.api时遇到的问题。我需要帮助才能在同步模式下调用FB.api()

for(var i = 0; i < commentObjectLength; i++){ 
    var fbFeedID = commentObject.OwnCommentList[i].fbFeedID; 
    var OwnCommentID = commentObject.OwnCommentList[i].OwnCommentID; 
    var accessToken = commentObject.OwnCommentList[i].accessToken; 
    var commentText = commentObject.OwnCommentList[i].commentText; 
    alert("Hiii"); // >>>>>>>1 

    FB.api('/' + fbFeedID + '/comments', 'post', { 
      message: commentText, 
      access_token : accessToken 
     }, function (response) { 
      if (!response || response.error){ 
       //alert(response.error.message); 
      } else { 
       alert("Hello"); // >>>>>>>2 
       alert(response.id); // >>>>>>>3 
      } 
     }); 
} 

现在来简单说一下。
我在警报期待出像
1-> HIII
2->你好
3->一些响应ID
4-> HIII
5->你好
6->一些resonse ID

但在现实中我得到了像
1-> HIII
2-> HIII
3-> HIII

持续到环的大小
8->你好
9->一些响应ID
10->你好
11->一些响应ID继续

问题是所有的时间循环的最后日期将去到Facebook和评论饲料。不分开。

所以请任何人帮我解决这个问题。我挣扎很多。
(希望每个人能够明白的问题,请需要问什么额外的信息)

回答

0

FB。*基于事件有一些技巧,使之更加同步,但它不会真的工作。你需要链接你的函数调用。

for(var i = 0; i < commentObjectLength; i++){ 
    var fbFeedID = commentObject.OwnCommentList[i].fbFeedID; 
    var OwnCommentID = commentObject.OwnCommentList[i].OwnCommentID; 
    var accessToken = commentObject.OwnCommentList[i].accessToken; 
    var commentText = commentObject.OwnCommentList[i].commentText; 

    FB.api('/' + fbFeedID + '/comments','post',{ 
      message: commentText, 
      access_token : accessToken 
     }, function (response) { 
      alert("Hiii"); // >>>>>>>1 
      if (!response || response.error){ 
       //alert(response.error.message); 
      } else { 
       alert("Hello");// >>>>>>>2 
       alert(response.id); // >>>>>>>3 
      } 
     }); 
} 
0

你需要远一点去研究Closures它会给你这个问题的妥善解决。

闭包给你一种方法来保留所有的变量值在自己的函数调用中,这就是为什么当FB.api将返回你的代码的响应时,所有的局部变量将调用FB.api时具有相同的值。我相信这会解决你的问题。