排序对象数组不起作用

时间:2017-04-05 02:54:55

标签: javascript sorting firebase firebase-realtime-database promise

我正在使用Firebase,并且需要在完成加载后对数据库项(名为“adsets”)执行排序。我将每个'adset'项添加到数组'adsets'中。完成所有计算后,我将'adsets'排序为'adsetDeviation'。问题是这根本不起作用 - adsets数组中的对象没有排序:

  function main() {
    ...
   //Irrelvant code ommitted

    var adsets = [];

    //Create promise that resolves once all the calculations are done for all the adsets
    var adsetPromise = new Promise(function(resolve, reject) {
      for (var currentAdsetId in campaign.adsets) {
        loadAdsets(currentAdsetId, adsets);
      }

      //Resolve the promise
      resolve(adsets);

    });

   //Sort and print full adset list
    adsetPromise.then(function(fullList) {
      console.log('by Deviation:');
      // Sort the adsets by Deviation 
      fullList.sort(function(a, b) {
        return a.adsetDeviation - b.adsetDeviation
      });
      console.log(fullList);
    });
  }

  function loadAdsets(adsetId, adsets) {
    firebase.database().ref('/adsets/' + adsetId).once('value').then(function(snapshot) {
      var adset = snapshot.val();

      adset.adsetDeviation = Math.ceil(adset.flight - adset.budget);

      adsets.push(adset);
    });
  }

控制台打印出来:

console

为什么不按adsetDeviation顺序排序?

0 个答案:

没有答案