浏览器可以在处理 post 请求之前处理脚本

Browser can process scripts before handle post request

浏览器可以在处理 post 请求之前处理脚本。考虑一下我有以下样本

if (some true condition) {
   console.log("ready to post")
   restangular.all.post(RequestData).then(function(response){
      //some post methods
      console.log("response")
   });       
}
//then containing scripts
cosole.log('Hello')
....

输出

准备好 post 你好 回应

我希望在打印 "Hello" 之前执行 POST 请求。如何克服这个问题?

为了实现您想要的效果,您应该查看 angularJS promises,因为 POST 请求是异步的。例如检查这个 link: http://www.webdeveasy.com/javascript-promises-and-angularjs-q-service/

主要思想是首先创建一个 returns 一个 deferred 对象的调用,例如

this.myFunction = function (myForm) {
    var deferred = $q.defer();
    $http.post(myURL, myForm)
        .success(function (data) {
            //resolve the promise
            deferred.resolve('SUCCESS');
        })
        .error(function (data) {
            //reject the promise
            deferred.reject('ERROR');
        });

    //return the promise
    return deferred.promise;
}

然后像这样称呼它

    var myPromise = this.myFunction ($scope.modalForm);
    // wait until the promise return resolve or eject
    //"then" has 2 functions (resolveFunction, rejectFunction)
    myPromise.then(function(resolve){
       // do stuff here, the post request is successfully finished
    }, function(reject){
        return;
    });

或者,任何你想在 POST 请求之后执行的代码,你可以把它放在请求的 success 函数中。