jQuery 使用 Trello API 嵌套每个循环未按预期工作

jQuery nested each loop not working as expected using Trello API

目标是使用Trello API ( https://developers.trello.com/ ) 获取所有成员的图板,然后在每个图板下显示他们的卡片。

不完全确定这是否特定于 API 或 jQuery,但是嵌套的 each 循环无法按预期工作。下面的代码显示了我当前正在使用的脚本的一小部分。它当前显示所有图板标题,然后显示所有卡片,例如

<h1>Board 1</h1>
<h1>Board 2</h1>
<h1>Board 3</h1>
<li>Card 1 </li>
<li>Card 2 </li>
<li>Card 3 </li>

然后:

<h1>Board 1</h1>
<li>Card 1 </li>
<h1>Board 2</h1>
<li>Card 2 </li>
<h1>Board 3</h1>
<li>Card 3</li>

在 each 循环中添加一些控制台日志显示外部 each 循环首先完成所有内容,然后通过内部循环,这不是我想要的。

var onAuthorize = function() {
    updateLoggedIn();
    $("#output").empty();

    // Get users boards
    Trello.get('/member/me/boards', function(board){

        // Loop through all boards
        $.each(board, function(ix, board) {


           // If the board is not closed, then go through it.
            if(board.closed != true){
                  $( "#output" ).append( '<a href="' + board.url + '"><h1>' + board.name + "</h1></a>" );
                     console.log("go through baords");
                  // Get all the members cards
                  Trello.get('/members/me/cards', function(cards){ 

                        $.each(cards, function(ib, card) { 

                            if(card.idBoard == board.id){

                                $( "#output" ).append( '<li class="BoardID' + card.idBoard +'"><a href="' + card.url + '">' + card.name + "</a></li>" );
                                    console.log("go through cards");
                            }

                        });

                  });
            }

        }); 

    });

};

感谢任何帮助。

这是预期的行为,因为 ajax 请求是异步执行的

// Get users boards
Trello.get('/member/me/boards', function (board) {

    // Loop through all boards
    $.each(board, function (ix, board) {
        var $board = $('<a href="' + board.url + '"><h1>' + board.name + "</h1></a>").appendTo("#output");
        console.log("go through baords");

        // If the board is not closed, then go through it.
        if (board.closed != true) {
            // Get all the members cards
            Trello.get('/members/me/cards', function (cards) {
                if (cards.length) {
                    var $ul = $('<ul />').insertAfter($board);
                    $.each(cards, function (ib, card) {
                        if (card.idBoard == board.id) {
                            $ul.append('<li class="BoardID' + card.idBoard + '"><a href="' + card.url + '">' + card.name + "</a></li>");
                            console.log("go through cards");
                        }
                    });
                }
            });
        }
    });
});