Array loop problem - JavaScript [duplicate]

-2

When I try to loop, I do not even want to get into the for, I already checked and the array with the object is not empty, but it does not execute the loop ... Any ideas?

var caminho = [];

$.get("http://localhost/crocs/arquivo.json", function(data) {

    data = typeof data == 'string' ? JSON.parse(data) : data;

    data.forEach(function(elementoDaArray) {

        skuid = elementoDaArray.SkuId;
        valor = elementoDaArray.Valor;
        letra = elementoDaArray.Letra;
        imagem = elementoDaArray.Imagem;

        caminho.push({
            img: imagem,
            id: skuid
        })
    });
});


for (var i = 0; i < caminho.length; i++) {
    console.log(products[i].img);
}
    
asked by anonymous 11.10.2018 / 22:32

1 answer

0

$ .get is an asynchronous function, it takes a while to fetch the response from your address, but the code does not wait for the function to finish to continue running. In case, you are calling $ .get, and then trying to read the array before it even fills it, if you want to continue with your code only after receiving the $ .get response, place your loop inside the function. Other alternatives are working with callbacks or promises.

    
11.10.2018 / 23:26