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. 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. 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))
. Done like that, the console.log
will execute immediately (before the fetch
completes).
Use a function instead. (Example input to use: "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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.