尝试在链中使用fetch并使用回调获取数据

问题描述 投票:0回答:1

您好我一直在尝试使用获取链从两个API获取,fetch工作并使用getallproducts函数内的console.log正确显示数据但是当我尝试使用数据对displayproducts函数进行回调时,数据是无处可见。我不知道我到底做错了什么,或者我是否使用了错误的方法,但我一直在尝试多种获取方法。 promise.all似乎是一个解决方案,但也没有用。

showProductsPage函数

function showProductsPage() {
    var page = document.getElementById('products-page');

    hideAllPages();
    //getAllProducts();
displayproducts(getAllProducts);
    page.style.display = 'block';
}

数字产品功能

function getAllProducts(callback){
    var producten; 
var authors; 
    fetch(window.location.href+"api/products")
                .then(response => response.json())              
                .then(data => { 
                         producten = data.products;
                        console.log(data);   
                        callback(data)                
return fetch(window.location.href+"api/authors")
                }).then(response => response.json())              
                .then(data => { 
                         authors = data.authors;
                    callback(data)
                })

}

展示产品功能

function displayproducts(data) {
    console.log(data.products);
    for (var i = 0; i < data.products.length; i++) {

    var card = document.createElement("div");
    var img = document.createElement("img");
    var name = document.createElement("BUTTON");
    var author = document.createElement("p");
    var published = document.createElement("p");
    var price = document.createElement("p");
    var cart = document.createElement("BUTTON");
    document.getElementById("products-page").appendChild(card); 
    //
    card.appendChild(img);
    card.appendChild(name);
    card.appendChild(author);
    card.appendChild(published);
    card.appendChild(price);
    card.appendChild(cart);
    //
    card.setAttribute("class", "book-card");
    img.setAttribute("class", "product-img");
    name.setAttribute("class", "book-title");
    author.setAttribute("class", "author");
    published.setAttribute("class", "published");
    price.setAttribute("class", "price");
    cart.setAttribute("class", "add-to-cart");
    //
    cart.innerHTML = "Add to Cart";
    name.innerHTML = data.products.title;
    price.innerHTML = data.products.price;
};
  //console.log(producten[1].price);
}
javascript api fetch
1个回答
0
投票

你混淆了电话。这个:

 displayproducts(getAllProducts)

一定是:

 getAllProducts(displayproducts);
© www.soinside.com 2019 - 2024. All rights reserved.