javascript - 在继续之前确保异步 GET/POST 请求已完成

标签 javascript post get firefox-addon firefox-addon-sdk

嘿,大家好,我在过去的几个小时里一直在尝试解决这个问题,并决定在 sleep 之前把它扔在这里,无论如何,问题是我需要确保 GET/POST 请求得到 100% 处理在继续代码之前,我用 firefox addon sdk 中的计时器巧妙地解决了这个问题,但因为这是 java 脚本,它锁定了 ui,所以我一直在寻找解决方案,并且偶然发现了 Felix Kling 的一个潜在解决方案,“How do I return the response from an asynchronous call?”。虽然我尝试过但没有成功,所以我想知道是否有人可以告诉我我做错了什么,或者我什至不能使用这个解决方案来完成我想做的事情。

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 记录“0”,后跟 GET 中的“OK”,然后其中一个捕获发生,所以我知道信息正在存储到数组中,只是我开始时的相同问题仍然存在。

如有任何帮助,我们将不胜感激。

最佳答案

如果您在继续之前需要返回响应,那么您实际上有两种选择:一种是将响应传递到 AJAX 响应处理程序中的回调中。一旦收到响应,回调将是应用程序继续的入口点。

另一个选项是使用同步 XHR 请求。然而,这种方法的缺点是您的 UI 将被锁定,直到请求完成。

干杯

关于javascript - 在继续之前确保异步 GET/POST 请求已完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20102135/

相关文章:

ajax - AngularJS 使用 $http.get 请求以特定顺序传递参数数据

javascript - 用 jquery 替换 html 按钮

javascript - 如何在页面加载时随机播放视频?

javascript - 如何将数据表内容存储在本地存储中

javascript - 带有 mouseenter 和 mouseleave 事件的菜单

c# - 使用 HttpClient 通过 HTTP POST windows phone 8.1 上传图像和字符串

json - 如何在 delphi 中使用 THTTPClient 发布 json?

jquery - 将商品添加到购物车 jquery 函数

Android - 使用 HTTP GET 读取 XML 文件

c# - 招摇发送空值