This question already has answers here:
How do I return the response from an asynchronous call?
                                
                                    (38个答案)
                                
                        
                        
                            Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
                                
                                    (6个答案)
                                
                        
                2年前关闭。
            
        

我无法从“ valores”数组中打印任何项目。我不知道发生了什么我在做一个sintaxis错误吗?当我做一个console.log(valores.length)结果为0。

var valores = new Array();

fetch("https://mindicador.cl/api")
.then (data => data.json())
.then (data => {
    valores["dolar"] = data.dolar.valor;
    valores["euro"] = data.euro.valor;
    valores["utm"] = data.utm.valor;
    valores["uf"] = data.uf.valor;
});

for (var index in valores){
    document.write(valores[index]+"<br>");
}

最佳答案

你的问题是时间。您向服务器承诺信息,并填充valores数组。但是问题是您在执行以下代码后立即执行for循环:

for (var index in valores){
    document.write(valores[index]+"<br>");
}


您需要在document.write方法中处理then

.then (data => {
    valores["dolar"] = data.dolar.valor;
    valores["euro"] = data.euro.valor;
    valores["utm"] = data.utm.valor;
    valores["uf"] = data.uf.valor;
    for (var index in valores){
        document.write(valores[index]+"<br>");
    }
});

10-07 18:30