0

I'm trying to populate a table with stuff, but when I run on the browser the data isn't showed. I tried outputing in the dev console the length of the stuff array and first it shows the correct value, but when I call the function to populate the table the content of the array dissapears.

Here's the code:

const PRODUCT_CART_URL = "https://japdevdep.github.io/ecommerce-api/cart/654.json";
var cpArray = [];

var getJSONData = function(url){
    var result = {};
    return fetch(url)
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw Error(response.statusText);
            }
        })
        .then(function(response) {
            result.status = 'ok';
            result.data = response;
            return result;
        })
        .catch(function(error) {
            result.status = 'error';
            result.data = error;
            return result;
        });
}

function fetchCartProducts() {
    getJSONData(PRODUCT_CART_URL).then(function(resultObj) {
        if (resultObj.status === "ok") {
            cpArray = resultObj.data.articles;
            console.log(cpAray.length); // It's 2 as it sould be
        }
    });
}

function showCartProducts() {
    let newHTML = "";
    let pTable = document.getElementById("products_table");
    console.log(cpArray); // It's 0, how???
    for (let i = 0; i < cpArray.length; i++) {
        console.log("Iteración 1");
        newHTML += `<tr>
                                <td data-th="Product">
                                    <div class="row">
                                        <div class="col-sm-2 hidden-xs"><img class="prod-img" src="` + cpArray[i].src + `" alt="Foto del producto" class="img-responsive"/></div>
                                        <div class="col-sm-10">
                                            <h4 class="nomargin">` + cpArray[i].name + `</h4>
                                            <p>Descripción del producto</p>
                                        </div>
                                    </div>
                                </td>
                                <td data-th="Precio: ">` + cpArray[i].currency + " " + cpArray[i].unitCost`</td>
                                <td data-th="Quantity">
                                    <input type="number" class="form-control text-center" value="1">
                                </td>
                                <td data-th="Subtotal" class="text-center">1.99</td>
                                <td class="actions" data-th="">
                                    <button class="btn btn-info btn-sm"><i class="fa fa-refresh"></i></button>
                                    <button class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>                                
                                </td>
                            </tr>`;
    }
    
    pTable.innerHTML = newHTML;
}

document.addEventListener("DOMContentLoaded", function() {
    fetchCartProducts();
    showCartProducts();
}); 

How is this possible? I cannot find where my code is wrong.

Lorena
  • 21
  • 5
  • 2
    You need to call `showCartProducts()` in the callback function of `fetchCartProducts()`. Your code isn't waiting for the array to be populated by the async functions. – Barmar Sep 28 '20 at 22:05
  • 1
    async functions don't execute in order like you expect them to. this is a duplicate of this question: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – bryan60 Sep 28 '20 at 22:06
  • Thanks guys, I didn't know that, now it's working – Lorena Sep 28 '20 at 22:17

0 Answers0