如何使2个异步API调用一个接一个地执行

时间:2013-06-26 14:59:24

标签: javascript api asynchronous

我正在使用facebooks javascript API从Facebook页面导入albumsphotos

首先,我使用API​​调用导入albums

然后我将每个photos的{​​{1}}导入到另一个API调用的数组中。

最后一步 - 通过另一个API调用,我导入每个相册的album,这样我就可以使用coverPhotos及其jquery mobile listView来制作albums。< / p>

我的代码如下所示:

coverPhotos

我在这段代码中遇到了问题:

<script>
    var albumPhotos = new Array();
    var albumThumbnails = new Array();
    window.fbAsyncInit = function() {
        // init the FB JS SDK 
        FB.init({
            appId      : '564984346887426',       // App ID from the app dashboard
            channelUrl : 'channel.html',          // Channel file for x-domain comms
            status     : true,                    // Check Facebook Login status
            xfbml      : true                     // Look for social plugins on the page
        });

        // Additional initialization code such as adding Event Listeners goes here
        FB.api('169070991963/albums', function(response) {
            if(!response || response.error) {
                // render error
                alert("Noo!!");
            } else {
                // render photos
                for(var i=0; i<response.data.length; i++) { 
                    (function (i) {
                        var albumName = response.data[i].name;
                        var albumCover = response.data[i].cover_photo;
                        var albumId = response.data[i].id;
                        var numberOfPhotos = response.data[i].count;

                        FB.api(albumId + "/photos", function(response) {
                            if(!response || response.error) {
                                // render error
                                alert("Noo!!");
                            } else {
                                for(var k=0; k<response.data.length; k++) { 
                                    albumThumbnails[i] =  albumThumbnails[i]||[];
                                    albumThumbnails[i][k] = response.data[k].picture;
                                    albumPhotos[i] = albumPhotos[i]||[];
                                    albumPhotos[i][k] = response.data[k].source;
                                }
                            }
                        }); 

                        console.log(albumName);
                        FB.api( albumCover, function(response) {
                            if(!response || response.error) {
                                // render error
                                alert("Noo!!");
                            } else {
                                // render photos
                                $(".albums").append(
                                    '<li>'+
                                        '<a href="#Gallery' + i + '"' + 'data-transition="slidedown">'+
                                            '<img src= "' + response.picture + '"  />'+
                                            '<h2>' + albumName + '</h2>'+
                                            '<p>' + "Number of Photos:  " + numberOfPhotos +'</p>'+
                                        '</a>'+
                                    '</li>')
                                    .listview('refresh');

                                $("#home").after('<div data-role="page" data-add-back-btn="true" id=Gallery'+ i +
                                    ' class="gallery-page"> ' +
                                    ' <div data-role="header"><h1>Gallery</h1></div> ' + ' <div data-role="content"> ' +
                                    ' <ul class="gallery"></ul> ' + ' </div> ' +
                                    ' </div> ');

                                for(var x=0; x < albumPhotos[i].length; x++)
                                    $('#Gallery' + i + ' .gallery').append('<li><a href="' + albumPhotos[i][x] + '" rel="external"><img src="' +  albumThumbnails[i][x] + '" /></a></li>');                                                             
                            }
                        });                             
                    })(i);                                      
                } //end of for loop
            }
        });     
    };

,更具体地说:for(var x=0; x < albumPhotos[i].length; x++) $('#Gallery' + i + ' .gallery').append('<li><a href="' + albumPhotos[i][x] + '" rel="external"><img src="' + albumThumbnails[i][x] + '" /></a></li>');

由于对API的调用是异步的,因此实际创建数组albumPhotos[i].length的先前API调用尚未完成,这意味着数组尚未定义

在拨打最后一次API调用albumPhotos

之前,我需要一种方法

确保以前的API调用:

FB.api(albumCover, function(response) {..}

已经结束。

在这里做这样的事情的最简单方法是什么?

1 个答案:

答案 0 :(得分:3)

简短的回答,您需要在填充后填写依赖于填充的相册的所有代码。这意味着复制和粘贴一些代码。

答案很长......

首先,让我们重构一下。为了您的理智,您将需要此功能

// checkForErrorFirst wraps your function around the error checking code first
// if there is no response, then your code will not be called
// this allows you to just write the juicy working code 
//   and not worry about error checking
function checkForErrorFirst(myFunc) {
  return function(response) { 
    if (!response || response.error) {
      alert("Noo!!");
    } else {
      myFunc(response);
    }
  };
}

这样你就可以做到这样的事情:

function DoWork(response) {
  // usefulwork...
}

FB看起来像......

FB.api('169070991963/albums', checkForErrorFirst(DoWork));

既然我们已经解决了这个问题,我们需要将你们的每一个电话联系在一起,因为它们彼此依赖。我像你一样在全球空间设置了albumPhotos和albumThumbnails。

var albumPhotos = new Array();
var albumThumbnails = new Array();

function getAlbums(response) {
  for (var i=0; i < response.data.length; ++i) {
    processAlbum(response.data[i], i);
  } 
}

function processAlbum(album, i) {
  FB.api(album.id + "/photos", checkForErrorFirst(populateAlbum(album, i)));
}

function populateAlbum(album, i) {
  return function(response) {
    for (var k=0; k < response.data.length; ++k){ 
      albumThumbnails[i] =  albumThumbnails[i]||[];
      albumThumbnails[i][k] = response.data[k].picture;
      albumPhotos[i] = albumPhotos[i]||[];
      albumPhotos[i][k] = response.data[k].source;
    }

    // now that we've populated the album thumbnails and photos, we can render the album
    FB.api(album.cover_photo, checkForErrorFirst(renderAlbum(album, i)));
  };
}

function renderAlbum(album, i) {
  return function(response) {
    var albumName = album.name;
    var albumCover = album.cover_photo;
    var albumId = album.id;
    var numberOfPhotos = album.count;

    // render photos
    $(".albums").append('<li>'+
      '<a href="#Gallery' + i + '"' + 'data-transition="slidedown">'+
      '<img src= "' + response.picture + '"  />'+
      '<h2>' + albumName + '</h2>'+
      '<p>' + "Number of Photos:  " + numberOfPhotos +'</p>'+
      '</a>'+
      '</li>').listview('refresh');

    $("#home").after('<div data-role="page" data-add-back-btn="true" id=Gallery'+ i +
     ' class="gallery-page"> ' +
     ' <div data-role="header"><h1>Gallery</h1></div> ' + ' <div data-role="content"> ' +
     ' <ul class="gallery"></ul> ' + ' </div> ' +
     ' </div> ');


    for(var x=0; x < albumPhotos[i].length; x++)
      $('#Gallery' + i + ' .gallery').append('<li><a href="' + albumPhotos[i][x] 
        + '"  rel="external"><img src="' +  albumThumbnails[i][x] + '" /></a></li>');
  };
}

// start the entire process
FB.api('169070991963/albums', checkForErrorFirst(getAlbums));

显然我没有测试过这个 - 但我认为这会对你的理智有所帮助。