尝试从javascript中的异步调用创建数组时的回调

时间:2015-12-16 14:23:14

标签: javascript asynchronous callback

我试图使用一个使用for循环的函数从异步get请求创建一个数组,以便在get请求中传递一个参数。

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

我无法弄清楚如何使用回调来完成这项工作。

2 个答案:

答案 0 :(得分:1)

一个选项是增加一个计数器以检查你是否在最后一个回调中,然后在最后一个回调中做任何需要的操作

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();

答案 1 :(得分:0)

等待所有这些异步事件发生,需要使用结果的代码应该在它自己的回调中,该回调在结果可用时运行。例如:

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);
 });

示例(使用image onload fn来模拟你的asysnc调用):http://codepen.io/RwwL/pen/VeeEBR?editors=001