[英]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.