如何等待 Http 请求完成?

how to wait for Http request complete?

我编写了 javascript 应用程序“Blackjack”,我需要使用一些 api。 首先,我创建了一个牌组并请求 returns 我的牌组 ID。


            fetch('https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1')
            .then(response => response.json())
            .then(data => {
                console.log(data.deck_id);
                deckId = data.deck_id;
            });

然后我要抽卡

           for(let i = 0; i < 2; i++)
           {
               for (let x = 0; x < players.length; x++)
                {
                    fetch('https://deckofcardsapi.com/api/deck/' + deckId + '/draw/?count=1')
                    .then(response => response.json())
                    .then(data => {
                        console.log(data.remaining);
                        deckLenght = data.remaining;
                        data.cards.map((card)=>
                        {
                            var newCard = getCardData(card);
                            players[x].Hand.push(newCard);
                            renderCard(newCard, x);
                            updatePoints();
                            updateDeck();
                        });
                    });
                }
            }

但是当我发送这个请求时,我的牌组 ID 是未定义的。 如何解决?

您需要将 for 循环放入第一个 HTTP 请求的 .then() 处理程序中。这样它将在您的请求完成后执行,而不是与其并行执行:

fetch('https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1')
  .then(response => response.json())
  .then(data => {
    console.log(data.deck_id);
    const deckId = data.deck_id;
    for(let i = 0; i < 2; i++) {
      for (let x = 0; x < players.length; x++) {
        fetch('https://deckofcardsapi.com/api/deck/' + deckId + '/draw/?count=1')
          .then(response => response.json())
          .then(data => {
             console.log(data.remaining);
             const deckLength = data.remaining;
             data.cards.map((card) => {
               var newCard = getCardData(card);
               players[x].Hand.push(newCard);
               renderCard(newCard, x);
               updatePoints();
               updateDeck();
             });
           });
       }
     }
  });