繁体   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