0

I am trying to create an array from an asynchronous get request using a function that uses a for loop in order to pass a parameter in the get request.

var loadRarity = function () {

       var rarities = [];

       for (var i =0; i < deck.length; i++) {

           Card.get({cardName: deck[i].card_name}, function(data) {

               rarities.push(data.data[0].rarity);
               console.log(rarities); //20 instances where the array is being populated

            });   
        console.log(rarities);// result :20x [] empty array
        }
        return rarities;

 };
 var raritiesArray = loadRarity();
 console.log(raritiesArray); //empty array

I can't figure out how to use the callback to make this work.

2 Answers 2

1

An option is to increment a counter to check if you are on the last callback an then do any needed operation in that last callback

var loadRarity = function () {

       var rarities = [];

       var counter = 0; // initialize counter

       for (var i =0; i < deck.length; i++) {

           Card.get({cardName: deck[i].card_name}, function(data) {

               counter += 1; //increment counter

               rarities.push(data.data[0].rarity);
               console.log(rarities); //20 instances where the array is being populated

               if(counter == deck.length){ //if true you are in the last callback
                 console.log(raritiesArray); // array with all the elements
               }

            });   
        }
        return rarities;

 };
 var raritiesArray = loadRarity();
Sign up to request clarification or add additional context in comments.

2 Comments

In this way I'm able to console.log a right result but I think this is happening because I'm calling it from inside the asynchronous function itself. In other words I cannot use the array after it's being created.
Hey @mosmic I will advice to check the use of promises, this will really help to tackle many async problems in general Link.Native implementations are ready on Emacs6 browser, and they are also libraries that implemented it.
0

Waiting for all this async stuff to happen, your code that needs to use the result should be in its own callback, which runs when the result is available. For example:

var loadRarity = function(cb) {
  var rarities = [],
      counter = 0,
      done = function(){
        if(counter++ === deck.length - 1){
          cb(rarities);
        }
      };
  for (var i =0; i < deck.length; i++) {
    Card.get({cardName: deck[i].card_name}, function(data) {
      rarities.push(data.data[0].rarity);
      done();
    });   
  }
 };
 loadRarity(function(completedRarities){
   console.log(completedRarities);
 });

Sample (using an image onload fn to simulate your asysnc call): http://codepen.io/RwwL/pen/VeeEBR?editors=001

7 Comments

Thank you very much for your answer. I tried your code and even though no error is returned still it logs nothing. The array is incrementally being populated as I console log it after the done(i); line but the console.log(completedRarities) prints nothing at all.
Have you logged/breakpointed inside the done function to see if it's getting into that if clause at all where it runs cb()?
Re-using i might be a crazy thing to do here too, you might try an independent counter var like in the other answer.
How would I check if done function is working the right way? As far as the other answer, I'm able to get a correct console.log result but i think this is happening because I call it from inside the async function. Meaning that this result exists only there. Maybe I'm wrong but consloling the raritiesArray in the globar scope returns nothing...
Check out the CodePen I just attached to the answer, you can verify that completedRarities is logged from the callback that you pass into loadRarity.
|

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.