v2.5.2
Giriş yap

JavaScript objeler ve diziler

egemen
300 defa görüntülendi

merhabalar js'te classlar ile çalışırken bir yerde takıldım. bilmediğim bişey var fakat çözüm bulamadım.

    class Product {
    constructor(id, title, price, image, description, category) {
        this.id = id
        this.title = title
        this.price = price
        this.image = new URL(image,
            import.meta.url)
        this.description = description
        this.category = category
    }
}
class Products {
    constructor() {
        this.products = []
        this.fetchProducts()
    }
    fetchProducts() {
        fetch('https://fakestoreapi.com/products')
            .then(res => res.json())
            .then(json => {
                json.forEach(element => {
                    this.products.push(new Product(element.id, element.title, element.price, element.image, element.description, element.category))
                });
            })
    }
}

const test = new Products();

console.log(test.products[0]); // undefined
class Test {
    constructor(name, surname) {
        this.name = name
        this.surname = surname
    }
}
let arr = []
arr.push(new Test("name1", "surname1"))
arr.push(new Test("name2", "surname2"))
console.log(arr[0].name) // name1
Cevap yaz
Cevaplar (2)
ebykdrms
761 gün önce

Merhaba. Siz Products class'ınızın fetchProducts() fonksiyonunda asenkron bir işlem yapıyorsunuz. Bu nedenle siz console.log yaptığınız sırada henüz https://fakestoreapi.com/products adresine yaptığınız isteğe yanıt dönmemiş oluyor. Promise yardımıyla cevabın dönmesini beklemeli, ürünleri daha sonra yazdırmalısınız.

class Product {
    constructor(id, title, price, image, description, category) {
        this.id = id;
        this.title = title;
        this.image = new URL(image, import.meta.url);
        this.price = price;
        this.description = description;
        this.category = category;
    }
}

class Products {
    constructor () {
        this.products = []; // Kurucu fonksiyonlarda asenkron işlemlere izin verilmiyor.
    }
    fetchProducts() { // fetch() fonksiyonunu return etmem gerekiyor.
        return fetch('https://fakestoreapi.com/products').then(res => res.json()).then(json => {
            json.forEach(element => {
                this.products.push(new Product(element.id, element.title, element.price, element.description, element.category))
            });
        });
    }
}

const test = new Products();

new Promise(async function() { // fonksiyonumuz asenkron bir fonksiyon
    await test.fetchProducts(); // önce fetchProducts() fonksiyonunun sonuç dönmesini bekliyoruz.
    console.log(test.products); // sonra ürünleri konsola yazdırabiliyoruz.
});