在promise之后或在promise内部返回值

Return value after promise or since inside promise

本文关键字:promise 返回值 内部 之后      更新时间:2023-09-26

我试图在promise结束后获得一个值结果。但是,如果我在函数的末尾放一个返回结果,它总是返回true。在末尾的promise中,值变为false。我是怎么做到的?

下面是我的代码示例:

function validations(){
    result = true;
    getDistance().then(function(response) {
        var distance = (response.rows[0].elements[0].distance.text).split(" ")[0];
        if(distance>=100)
            result = false;
        return result;
    }
 }

在这种情况下,当我需要一个true/false值时,我的函数是"未定义的"。当我把返回结果放在末尾时,它总是返回true。

function validations(){
result = true;
    getDistance().then(function(response) {
        var distance = (response.rows[0].elements[0].distance.text).split(" ")[0];
       if(distance>=100)
        result = false;
    }
  return result
 }

您有两个选项。你可以使用Promise模式:

function validations() {
    return getDistance().then(function(response) {
        var distance = (response.rows[0].elements[0].distance.text).split(" ")[0];
        return distance>=100;
    });
}
validations().then(function(trueOrFalse){
    //  trueOrFalse is true if distance was less than or equal to 100
});

或者回调模式:

function validations(cb) {
    getDistance().then(function(response) {
        var distance = (response.rows[0].elements[0].distance.text).split(" ")[0];
        cb(null, distance>=100);
    }, cb);
}
validations(function(error, trueOrFalse){
    //  trueOrFalse is true if distance was less than or equal to 100  
});

在任何一种情况下,需要注意的重要一点是,在设置值之前,您都不会试图执行依赖于该值的代码。