Dante
Dante

Reputation: 33

how to wait for Http request complete?

I write javascript app "Blackjack" and I need use some api. First I created a deck and request returns me deck 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;
            });

And then I want to draw cards.

           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();
                        });
                    });
                }
            }

But when I send this request my deck id is undefined. How to fix that?

Upvotes: 0

Views: 231

Answers (1)

Anton
Anton

Reputation: 472

You need to put your for loop into the .then() handler of the first HTTP request. That way it will be executed after your request finishes, not in parallel to it:

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();
             });
           });
       }
     }
  });

Upvotes: 1

Related Questions