0
我正在使用Azure移動服務和一個JavaScript後端。我的問題是該函數不會等待其他函數的結束。蔚藍的異步JavaScript後端 - 等待函數
我試圖選擇一個具有特殊規則的項目(單詞)。我想選擇item.wordnumber最高的項目。如果有少量項目具有相同的item.wordnumber,我想選擇與該項目相關的投票的最高票數(在另一個表中爲「投票」)。
此腳本不會等待函數CalcolateMaxAvg的返回。 我會盡我所能在C#中等待。
var tableWords = tables.getTable('Word');
var tableVotes = tables.getTable('Votes');
var avgVotesActualWord = 0;
var maxItem = null;
var maxItemVote = 0;
function WordChoice() {
var select = tableWords.orderByDescending('wordnumber').read({success:
function (results)
{
results.forEach(function(item)
{
if(maxItem == null)
{
maxItem = item;
maxItemVote = tableVotes.where({idword: item.id}).read({success: CalcolateMaxAvg});
}
else if(item.wordnumber > maxItem.wordnumber)
{
maxItem = item;
maxItemVote = tableVotes.where({idword: item.id}).read({success: CalcolateMaxAvg});
}
else if(item.wordnumber == maxItem.wordnumber)
{
//chack who have more votes
avgVotesActualWord = 0;
avgVotesActualWord = tableVotes.where({idword: item.id}).read({success: CalcolateMaxAvg});
//the problem is avgVoteActualWord that is always NaN
console.log('Word: %s with avg: %d', item.word, avgVotesActualWord);
if(avgVotesActualWord > maxItemVote)
{
//take the actualword because have more votes
maxItem = item;
maxItemVote = avgVotesActualWord;
}
}
})
if(maxItem != null)
{
console.log('parola: %s', maxItem.word);
maxItem.selected = true;
tableWords.update(maxItem);
}
else
{
console.log('null');
}
}
});
}
function CalcolateMaxAvg(resultsVote)
{
var sum = 0;
var count = 0;
var avg = 0;
resultsVote.forEach(function(itemVote)
{
sum = sum + itemVote.vote;
count = count + 1;
})
if(count > 0)
{
avg = sum/count;
}
//this is a correct value of avgVoteActualWord, but he don't wait the return of this value
console.log('avg: %d', avg);
return avg;
}
它的工作原理!謝謝!! – damiano