浏览器可以在处理发布请求之前处理脚本。请考虑我有以下示例
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')
....
准备发布 你好 响应
我希望在打印“Hello”之前执行POST请求。如何克服这个?
答案 0 :(得分:3)
为了达到你想要的效果,你应该研究 angularJS promises ,因为POST请求是异步的。例如,检查此链接: http://www.webdeveasy.com/javascript-promises-and-angularjs-q-service/
主要思想是首先创建一个返回延迟对象的调用,类似
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请求后执行的任何代码,您可以将其放在请求的成功函数中。