2017-02-14 7 views
1

這是我第一次來這裏,我真的失去了做什麼。AngularJS - API調用循環 - 獲取數組的最大值並設置響應

所以我有一個循環,我正在發送一個API的發佈請求。我需要發送一些問題,並讓他們的費率匹配回來。之後,我需要計算最高匹配度,並在$ scope變量中設置一個答案以顯示在屏幕上。 我遇到的問題是,由於調用是異步的,有時它會顯示錯誤的答案(因爲它是返回的最後一個響應)。 我知道它是異步的,我應該有一些回調,但我嘗試了很多方法,仍然無法弄清楚如何。我所需要的就是能夠對結果進行「排序」,以便在所有呼叫完成後,我可以獲得最大數量並顯示相關答案。我至今是:

for (var i = 0; i < $scope.possibleQuestions.length; i++) { 
      var compare = compareAPI($scope.results, $scope.possibleQuestions[i].question, 
         $scope.possibleQuestions[i].answer, 
         $scope.possibleQuestions[i].keywords, 
         $scope.possibleQuestions[i].similar, 
      function (score, question, answer, keywords, similar) { 
       $scope.compareAPI = score.average; 

        if ($scope.compareAPI >= 0.6) { 
         realAnswer = answer; 
         questionsAskedCount++; 
         $scope.answer = realAnswer; 
        } else { 
         var isMatch = matchKeywordAPI(question, keywords); 
         if (isMatch == 0) { 
          $scope.answer = "Please try asking another question!"; 
         } 
         else { 
          //have to return a string just to know, bcause realAnswer is undefined in here, have to return callback function hahahahaha again, or set the answer in the match function 
          $scope.answer = realAnswer; 
         } 

        } 
      }); 
     } 

而其他功能:

function compareAPI (possibleQuestion, possibleAnswer, fn) { 
    console.log("compare API"); 

    var apiMatch = semanticService.getSemantic($scope.studentQuestion, possibleQuestion) 
    apiMatch.then(function (result) {   
     fn(result.data, possibleQuestion, possibleAnswer); 
     console.log(result.data); 
    }, function(error){ 
     $scope.status = 'Unable to load question data: ' + error.message; 
    }); 

} 

我最大的問題是,這部分

if ($scope.compareAPI >= 0.6) { 
    realAnswer = answer; 
    questionsAskedCount++; 
    $scope.answer = realAnswer; 
    } else { 
     var isMatch = matchKeywordAPI(question, keywords); 
     if (isMatch == 0) { 
      $scope.answer = "Please try asking another question!"; 
     } 
     else { 
      $scope.answer = realAnswer; 
     }       
} 

是隨機的,因爲異步的,因此,如果錯誤的答案是最後的迴應,它會轉到'其他'並且答案錯誤。

任何幫助將非常感謝!謝謝!

回答

0

承諾可以通過鏈接它們順序進行:

var promise = $q.when(null); 

for (let i=0; i<promiseArray.length; i++) { 
    promise = promise.then(function() { 
     //return promise to chain 
     return promiseArray[i]; 
    }); 
}; 

promise.then(function() { 
    console.log("ALL Promises Done"); 
}); 

欲瞭解更多信息,請參閱AngularJS $q Service API Reference - Chaining Promises.

+0

謝謝您的回答,但我還是不明白如何使用它們。我已經閱讀了許多有關承諾的文章,但仍然沒有任何作品。 在函數promise.then(...)我試圖訪問promiseArray [0],它仍然未定義。我需要一種方法來獲取所有這些值,如果稍後可以對它們進行排序,則不必按順序排序,但是我需要在循環之後得到它們。 –

相關問題