我正在使用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);
});
}
控制台打印出来:
为什么不按adsetDeviation顺序排序?