简体   繁体   English

Fetch()和array.push()之后数组为空

[英]Array Empty After Fetch() and array.push()

I have a fetch call to an API that iterates over the returned JSON using callbacks and then I want to output the result into the console. 我有一个对API的访存调用,该API使用回调对返回的JSON进行迭代,然后将结果输出到控制台。 The issue is that I feel like even though this should be doing it asynchronously, I am using the then() call, which I was under the impression it would wait for the return and print out properly. 问题是我感觉即使这应该异步进行,但我正在使用then()调用,我的印象是它将等待返回并正确打印。 But on the first call, it prints out an empty array in the console, then on the second button press it logs the array correctly. 但是在第一个调用中,它会在控制台中打印出一个空数组,然后在第二个按钮上按它可以正确记录该数组。

 function getPrice() { var valueArray = []; var symbol = document.getElementById("symbol_input").value; var url = "https://api.iextrading.com/1.0/stock/" + symbol + "/chart" fetch(url) .then(res => res.json()) .then(function(res) { res.forEach(element => { valueArray.push(element); }); }) .then(console.log(valueArray)) .catch(err => console.log(err)); } 
 <input type="input" id="symbol_input"> <button id="priceButton" onclick="getPrice()">Get Price</button> 

.then accepts a function as a parameter, not a plain statement like .then(console.log(valueArray)) . .then接受函数作为参数,而不是像.then(console.log(valueArray))这样的简单语句。 Done like that, the console.log will execute immediately (before the fetch completes). 这样做之后, console.log立即执行(在fetch完成之前)。

Use a function instead. 改用一个函数。 (Example input to use: "abc") (使用的示例输入:“ abc”)

 function getPrice() { var valueArray = []; var symbol = document.getElementById("symbol_input").value; var url = "https://api.iextrading.com/1.0/stock/" + symbol + "/chart" fetch(url) .then(res => res.json()) .then(function(res) { res.forEach(element => { valueArray.push(element); }); }) .then(() => console.log(valueArray)) .catch(err => console.log(err)); } 
 <input type="input" id="symbol_input"> <button id="priceButton" onclick="getPrice()">Get Price</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM