繁体   English   中英

如何等待 Http 请求完成?

[英]how to wait for Http request complete?

我写了 javascript 应用程序“二十一点”,我需要使用一些 api。 首先,我创建了一个牌组,请求返回我牌组 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 .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();
             });
           });
       }
     }
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM