likashing
likashing

Reputation: 13

JavaScript callbacks - issues with accessing individual elements of a returned array

Self-taught and struggling a little bit to understand how callbacks work.

My callback handling function cannot access individual elements of the array i.e:

However, "ResultsArray[1]" works perfectly fine when executed in Firefox console directly.

What am I doing wrong?

<script>
   ArrayOfTickers=["SPY","DIA","IWM","C"];
   ResultsArray=[];
   SomeArray=[]

   function Main(Array, callback){
       recursive(0);

       function recursive(counter) {

           if (counter < ArrayOfTickers.length) {
               fetch("https://api.iextrading.com/1.0/stock/" + ArrayOfTickers[counter] + "/time-series")
                   .then(function(response) {
                       response = response.json()
                       .then(function(data) {
                           ResultsArray[counter]=data
                       })
                    }) 
                recursive(counter+1);
            } else {
                callback(ResultsArray);
            };
        } //End recursive function
    };  //End Main Function.
    Main(ArrayOfTickers, function(ResultsArray){
        console.log(ResultsArray)
    })
</script>

Upvotes: 1

Views: 52

Answers (2)

Alexander Mills
Alexander Mills

Reputation: 99990

First, if you are going to use callbacks, use error-first callbacks like this:

const results = [];

function main(cb) {

  (function recursive(counter) {

    if (counter >= ArrayOfTickers.length) {
      return cb(null);
    }

    const url = `https://api.iextrading.com/1.0/stock/${ArrayOfTickers[counter]}/time-series`;

    fetch(url)
    .then(function (response) {
      return response.json();
    })
    .then(function (data) {
      results.push(data);
      recursive(counter + 1);
    })
    .catch(cb);

  })(0)

}

main(function (err) {
  if (err) throw err;
  console.log(results)
});

// but it might be better to use promises like so

function main() {

  const recursive = function (counter) {

    if (counter >= ArrayOfTickers.length) {
      return;
    }

    const url = `https://api.iextrading.com/1.0/stock/${ArrayOfTickers[counter]}/time-series`;

    return fetch(url)
    .then(function (response) {
      return response.json();
    })
    .then(function (data) {
      results.push(data);
      return recursive(counter + 1);
    });

  };

  return recursive(0);

}

main().then(function(){
  // check results
})
.catch(function(err){
   // handle error
});

Upvotes: 0

David Suh
David Suh

Reputation: 76

"console.log(ResultsArray)[1])"

Should be console.log(ResultsArray[1]), bad parentheses.

Upvotes: 1

Related Questions