简体   繁体   English

等待承诺解决后再执行代码

[英]Wait for promise to resolve before executing code

I have a service that calls a $http request and returns a JSONP . 我有一个服务,该服务调用$ http请求并返回JSONP。 The returned JSONP from the API is either {valid:true} or {valid:false}. 从API返回的JSONP是{valid:true}或{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(): 我还有另一个服务,该服务取决于从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) : 输出为(在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'

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. 我想知道如何等待then()完成,将value设置为truefalse ,然后转到if语句。

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). valid = response是异步的(当它被执行then被触发)。 You cannot use this value outside that context (ie in your if ). 您不能在该上下文之外(例如,在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 . 如果您需要使用响应,请在then函数中直接使用它,或者返回一个promise, thenthen处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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