[英]Making sure an asyncronous GET/POST request has completed before continuing
嗨,我在過去的幾個小時里一直在嘗試解決此問題,並決定在我睡覺之前將id塞在這里,無論如何,問題是我需要確保GET / POST請求已得到100%處理,然后再繼續的代碼,我hackly解決了這個來自Firefox的插件SDK中的計時器,而是因為這是Java腳本,它可以鎖定用戶界面,所以我一直在尋找一個解決方案,我在由費利克斯·克林一個潛在的解決方案迷迷糊糊的,“ 我如何返回異步調用的響應? ”。 盡管我沒有成功嘗試過,所以我想知道是否有人可以向我展示IVE做錯了什么,或者我什至不能使用此解決方案完成我想做的事情。
download_status(download_database());
function download_status(downloadStatus){
if(downloadStatus==0){
console.log(regexArray.length);
}
else{
console.log("oh no");
}
}
function download_database(){
var downloadDone = 0;
var requestDB = request.Request({
url: "http://phyzical.pythonanywhere.com/download_db/",
onComplete: function(response){
console.log(response.statusText);
if(response.json == null){
console.log("cannot retreive json properly.")
}
else{
var dbInfoLength = response.json.length;
var idNumber = 0;
for(var x=0;x<dbInfoLength;x++){
try{
var patt1=new RegExp(response.json[x].regex);
idArray[idNumber] = response.json[x].id;
regexArray[idNumber] = response.json[x].regex;
incorrectMessageArray[idNumber] = response.json[x].incorrect_information;
correctMessageArray[idNumber] = response.json[x].correct_information;
idNumber++;
}
catch(e){
console.log("The annotation with the id: \""+ response.json[x].id+" " + e.message + "\" is wrong.");
}
}
downloadDone = 0;
}
},
}).get();
return downloadDone;
}
可悲的是regexArray.length從GET中記錄“ 0”,然后是“ OK”,然后觸發了一個catch,因此我知道信息存儲在數組中只是因為我開始時遇到的同一問題仍然存在。
任何幫助,將不勝感激。
如果在繼續之前需要返回響應,則確實有兩種選擇:一種是將響應傳遞到AJAX響應處理程序中的回調中。 一旦收到響應,回調將是應用程序繼續運行的入口點。
另一個選擇是使用同步XHR請求。 但是,這種方法的缺點是您的UI將被鎖定,直到請求完成為止。
干杯
Addon SDK的promise模塊可以讓您優雅地做自己想做的事情。
我還沒有實現您的任何邏輯,但是我重寫了您的請求代碼(因為這是您遇到的麻煩),以使用jQuery的AJAX方法代替Firefox的請求。
<h1>JSON Data Fetch Test</h1>
<div id="data"></div>
<script src="jquery-2.0.3.min.js"></script>
<script>
var dataBlock = document.getElementById("data");
function GetData()
{
try
{
$.ajax({
url: "http://phyzical.pythonanywhere.com/download_db/",
crossDomain: true,
dataType: 'text',
context: document.body,
error: reportError
}).done(processResponse);
}
catch(e)
{
dataBlock.textContent = "Request Error: " + e.message;
}
}
function reportError()
{
dataBlock.textContent = "Some kind of problem...";
}
function processResponse(data)
{
dataBlock.textContent = data;
var obj = JSON.parse(data);
/*Do all the things you need to do with your data here.*/
}
dataBlock.textContent = "Fetching data...";
GetData();
</script>
我目前無法回答太多的代碼,但是當我遇到此類問題時,我通常最終會在Get的onComplete內調用“ next”函數(在您的情況下為download_status()),無論是硬編碼還是as回調。 這將確保它在完成后被調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.