简体   繁体   中英

Wait for promise to resolve before executing code

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.

You can never return a value from asynchronous function .

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

valid = response is asynchronous (it will be executed when then is triggered). You cannot use this value outside that context (ie in your if ). If you need to use the response, use it right there in the then function, or return a promise, and continue processing with another then .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM