0

I want to create a class Deck that gets two attributes id and remaining. I use the Deck of Cards API to get the information of a deck but every time I create a Deck I keep getting id and remaining as undefined and I don't understand why because the JSON value is good and when I print it I got something but my attributes are undefined.

 class Deck {

    constructor(numberOfDeck, jokersEnabled) {
        let url;

        if (jokersEnabled) {
            url = "https://www.deckofcardsapi.com/api/deck/new/shuffle/?deck_count=" + numberOfDeck + "&jokers_enabled=true";
        } else {
            url = "https://www.deckofcardsapi.com/api/deck/new/shuffle/?deck_count=" + numberOfDeck;
        }
        console.log(url);
        fetch(url).then(res => res.json()).then(value => {
            this.id = value.deck_id;
            this.remaining = value.remaining;
        }).catch(function(err) {
            console.log(err);
        });
    }
}

let deck = new Deck(1, true);
console.log(deck.id + " " + deck.remaining);
  • 3
    `fetch` is an asynchronous function as it returns a `Promise`, so by the time you log the various properties of the deck, `fetch` hasn't resolved yet. – CerebralFart Dec 07 '21 at 10:00
  • Well, whoever closed this as duplicate sure got some easy points. Anyway, if you want to make sure your Deck is ready to use after creating it, consider moving the fetch out of the constructor into a separete function and then constructing a Deck from its resolved value. If a Deck is created on page load or in response to a user action, it's fine if the event handler is asynchronous. – DustInComp Dec 07 '21 at 10:11
  • @DustInCompetent Im afraid that if we answered every async javascript question misunderstanding individually we'd need to change the name of the site to AsyncJavascriptOverflow :( there are literally hundreds of these questions per day. Also, you don;t get anything for closing as a dupe - just to clear up any misunderstanding. – Jamiec Dec 07 '21 at 10:13

0 Answers0