函数的意外未定义返回值

时间:2018-08-04 11:04:58

标签: javascript

我从函数中获得了意外的不确定的返回值。

function createselbox(arr) {
    console.log('In createselbox');
    var startstr = `Something`;
    mytemp = '';
    for (var i = 0; i < arr.length; i++) {
        mytemp = mytemp + '<option>' + arr[i] + '</option>';
    }
    var ret = startstr + mytemp + `Something else    `;
    IsStaff = CheckifStaff();
    console.log('Checkifstaff is ' + IsStaff);
    if (IsStaff) {
        console.log('Got true createselbox');
        console.log('In sel loop');
        ret = startstr + mytemp + `Something more`;
    } else {
        console.log('Got false createselbox');
    }
    return ret;
}

function CheckifStaff() {
    var data = {
        "isstaff": 'check'
    };
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
        type: "POST",
        dataType: "html",
        url: "/functions/checkifstaff",
        data: data,
        success: function (data) {
            var recdata = data;
            if (recdata.indexOf('Has add permissions') != -1) {
                console.log('Returning true');
                return 1;
            } else {
                console.log('Returning false');
                return 0;
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log('An error occured in CheckifStaff');
            return 0;
        }
    });
}

控制台显示:

In createselbox
appointment.js ? dev = 96168005 : 292 Checkifstaff is undefined
appointment.js ? dev = 96168005 : 305 Got false createselbox
appointment.js ? dev = 96168005 : 158 Returning true

createselbox首先被调用。但是,显然甚至在函数执行之前,该函数的值就被返回为false。

为什么会这样?

4 个答案:

答案 0 :(得分:1)

CheckifStaff()没有明确的return语句,因此它返回默认情况下所有函数返回的内容,即undefined

答案 1 :(得分:1)

要执行此操作,CheckiStaff需要返回一些内容,例如CheckiStaff将返回值为1或0的Promise。createselbox现在将await {{1 }},然后使用它随后返回的值

CheckiStaff

答案 2 :(得分:1)

您也可以将ajax更改为这样

 $.ajax({
    type: "POST",
    dataType: "html",
    url: "/functions/checkifstaff",
    data: data,
    success: function (data) {
        var recdata = data;
        if (recdata.indexOf('Has add permissions') != -1) {
            console.log('Returning true');
            return 1;
        } else {
            console.log('Returning false');
            return 0;
        }
    },
    error: function (xhr, textStatus, errorThrown) {
        console.log('An error occured in CheckifStaff');
        return 0;
    }
}).then(function(data){
   return data
});

答案 3 :(得分:0)

我不是专家,但是我认为当您使用ajax时,您应该等待响应-使用promise或async / await func