簡體   English   中英

等待承諾解決后再執行代碼

[英]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設置為truefalse ,然后轉到if語句。

您永遠不能從異步函數返回值

            data.then(function (response) {
                valid = response;
                console.log('Inside the then block : ' + valid);
            });

valid = response是異步的(當它被執行then被觸發)。 您不能在該上下文之外(例如,在if )使用此值。 如果您需要使用響應,請在then函數中直接使用它,或者返回一個promise, thenthen處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM