等待promise解析后再执行代码

Wait for promise to resolve before executing code

本文关键字:执行 代码 promise 等待      更新时间:2024-04-09

我有一个服务,它调用$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');
    })
}

我有另一个依赖于checkValidat()返回的响应的服务:

                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,然后使用另一个then继续处理。