0
我試圖從外部API計算結果的總和,我需要爲每個關鍵字我有一個請求。代碼執行成功,但函數在完成所有ajax請求之前返回值。 我嘗試添加「異步」參數,但它棄用然後我做了這個:cicle後AJAX返回變量完成
function calcTotal(arr) {
var t_docs = 0;
var i = 0;
var len = arr.length;
var aReq = []
for(i = 0; i < len; i++)
{
console.log(i);
var apiDataLQKT = {
keyword: arr[i],
start_date: "2015-01-01",
end_date: "2015-06-01",
format: 'jsonp',
sources_types: sources,
sources_names: names,
domains: argDomains,
words: terms,
author_id: usrID,
sentiment:sentiment,
positive_threshold:posThresh,
negative_threshold:negThresh,
language:lang,
author_location:geolocations,
author_gender:genderID,
typologies:typID,
document_type:docType,
source_base_url:'',
emotion:'',
metadata:'',
order_sort:'',
order_by:''
}
console.log(apiDataLQKT);
aReq[i] = $.ajax({
type:'GET',
url:apiUrl+'LightQuantitativeKeywordTrend',
contentType: 'application/javascript',
crossDomain: true,
dataType: 'jsonp',
data: apiDataLQKT,
success: function(json) {
var res = json.LightQuantitativeKeywordTrend;
t_docs += res.count;
console.log("T_DOCS[" + arr[i] + "]: " + t_docs);
}
});
}
aReq[arr.length-1].done(function(data){
return t_docs;
});
}
控制檯日誌輸出:
Total: 0
T_DOCS[undefined]: 1445
T_DOCS[undefined]: 1521
...
我還能嘗試一下呢?
您正在尋找承諾。有關如何延遲使用ajax調用的結果集的示例,請參閱['$ .when()'](https://api.jquery.com/jquery.when/),直到先前排隊的調用已返回。這聽起來像這是你問的。 – War10ck