所以我希望变量 pass_or_fail 在 .then 子句内部分配,并且该分配反射(reflect)在 .then 子句外部
this.$http.post('http://localhost:3000/signup?username='+this.username+'&password='+this.password+'&password2='+this.password2)
//make get request to API with what USER entered into the search bar in the query string
.then(response => {
if(response.body== "success"){
this.pass_or_fail=response.body;
}
}
)
console.log(this.pass_or_fail);
if(this.pass_or_fail=="success"){
this.$router.push({name:'landing-page'});
}
//set sources variable to our response
}
但是,当我在 .then 子句之外使用 console.log(this.pass_or_fail) 时,该变量尚未分配给response.body。知道为什么 .then 子句内部的更改没有反射(reflect)在子句外部吗?
最佳答案
该帖子是一个异步请求,这意味着当您记录 this.pass_or_fail
时,传递给 then
方法的函数尚未触发。
您需要根据传递给 then()
的函数内的 post 请求的结果放置任何代码:
this.$http.post('yoururl')
.then((response) => {
if (response.body == "success") {
this.pass_or_fail = response.body;
console.log(this.pass_or_fail);
this.$router.push({ name: 'landing-page' });
}
});
关于javascript - HTTP 请求的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43664532/