1

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>

1 Answer 1

6

.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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.