0

我正在尝试从 Facebook 图表中获取一些数据,但我遇到了一个小问题。看来第二个请求工作正常(使用注释控制台行检查)但是当我获得 response2 值并将其存储在 myEvents 数组中时,我尝试打印该值但它显示为 null。

 FB.api('me/events?fields=id,location', function(response) {

                    for (var i=0; i<response.data.length; i++) {

                        myEvents[i] = new Array(3);

                        myEvents[i][0]= response.data[i].id;
                        myEvents[i][1]= response.data[i].location;


                        //get number of attending people per event
                        var q = response.data[i].id+'/attending';
                        FB.api(q, function(response2) {

                            //console.log(response2.data.length); //check response
                            myEvents[i][2]=response2.data.length; //asign response value to array



                        });

                        console.log(myEvents[i][2]); //here show null instead of the assigned value
                    }
4

2 回答 2

0

这将是undefined因为您没有等待FB.api呼叫完成。由于它是异步事件,它不会立即结束。因此,console.log(myEvents[i][2]);将在API 调用完成并设置其值之前完成。

您需要正确处理异步调用,然后您还将获得参加人数的正确值。

于 2013-05-02T09:40:24.787 回答
0

调用FB.api不会停止执行。闭包和事件处理程序一样,提供了处理异步操作的方法。让我们再看看你的代码。

FB.api( 'me/events?fields=id,location',
  function(response) {
    // This code is executed once the outer async FB.api call (me/events) completes

    for ( var i=0; i<response.data.length; i++ ) {
      myEvents[i] = new Array(3);
      myEvents[i][0]= response.data[i].id;
      myEvents[i][1]= response.data[i].location;

      console.log( "Log A" );

      var q = response.data[i].id+'/attending';

      FB.api( q,
        function( response2 ) {
          // This code is executed once the inner async FB.api call (id/attending) completes

          myEvents[i][2]=response2.data.length;

          console.log( "Log C" );
        } );

      // This code is executed immediately after firing off the inner FB.api method.
      console.log( "Log B" );
    }
  } );

如果上面的编码示例找到 3 个事件,那么控制台将显示...

日志 A
日志 B
日志 A
日志 B
日志 A
日志 B
日志 C
日志 C
日志 C

这有助于澄清吗?这基本上是说你需要将你的console.log(myEvents[i][2]);日志移动到你的第二个闭包中。

于 2013-05-06T17:10:56.670 回答