0

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?

Dante
  • 43
  • 1
  • 7
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ben Fortune Aug 07 '20 at 14:04

1 Answers1

1

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();
             });
           });
       }
     }
  });
Anton
  • 440
  • 3
  • 10