[英]Wait for promise to resolve before executing code
我有一个服务,该服务调用$ http请求并返回JSONP。 从API返回的JSONP是{valid:true}或{valid:false}。 我的代码是:
this.checkValid = function () {
return $http({
method: 'JSONP',
url: 'API' + '?callback=JSON_CALLBACK',
}).then(function (response) {
var temp = response.data.valid;
return temp; //returns true or false
}, function (response) {
console.log('something went wrong');
})
}
我还有另一个服务,该服务取决于从checkValid()返回的响应:
var data = requestService.checkValid();
var valid;
//handling the promise
data.then(function (response) {
valid = response;
console.log('Inside the then block : ' + valid);
});
if (valid)
console.log('Valid!');
else
console.log('Not Valid!');
输出为(在api返回valid:true之后):
'Not valid'
'Not valid'
'Not valid'
'Not valid'
'Inside the then block : true'
'Inside the then block : true'
'Inside the then block : true'
'Inside the then block : true'
我想知道如何等待then()
完成,将value
设置为true
或false
,然后转到if
语句。
data.then(function (response) {
valid = response;
console.log('Inside the then block : ' + valid);
});
valid = response
是异步的(当它被执行then
被触发)。 您不能在该上下文之外(例如,在if
)使用此值。 如果您需要使用响应,请在then
函数中直接使用它,或者返回一个promise, then
与then
处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.