I have a service that calls a $http request and returns a JSONP . The returned JSONP from the API is either {valid:true} or {valid:false}. My code is:
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');
})
}
I have another service that depends on the response returned from 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!');
The output is (after the api returns 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'
I would like to know how to wait for the then()
to complete, setting value
to true
or false
, then going to the if
statement.