则未定义函数

then function is not defined

本文关键字:函数 未定义      更新时间:2023-09-26

我有一个函数来获取当前公司代码,我需要将其存储在本地存储上,并在其余的API调用中使用它。 因此,在未检索到此公司代码的值之前,我不应进行 API 调用。这就是我获取公司代码的方式

currentDivision = function() {
    var q = $q.defer();
    var division = window.localStorage.getItem("CurrentDivision");
    if(division){
        return q.resolve(division);
    }
    else{
        var url = this.fooApi + "current/Me?$select=CurrentDivision";
        $http.get(url)
            .success(function(data) {
                division = data.d.results[0].CurrentDivision;
                window.localStorage.setItem("CurrentDivision", division);
                return q.resolve(division);
            })
    }
    return q.promise;
}

这就是我在确保成功检索当前除法后尝试调用其余 API 调用的方式:

$scope.openModal = function() {
        $scope.modal.show().then(function() {
            currentDivision().then(function(){
            fooServices.getData().then(function() {
                $scope.closeModal();
            }, function(reason) {
                // handle the error
                $scope.showAlert(reason);
                $scope.closeModal();
            })
            });
        })
}

但是当我尝试这样做时,我收到以下错误消息:类型错误:无法读取未定义的属性"then"

您应该始终返回q.promise 。取出以下return

if (division) {
    return q.resolve(division);
}

即:

var q = $q.defer();
// ...
if (division) {
    q.resolve(division);
} else { 
  //...
}
return q.promise;

通过这种方式,您返回已经解决的承诺,这会立即调用then

试试这个:

if (division) {
    return $q.when(division);
}

并改进您的代码:

currentDivision = function () {
    if (division) {
        return $q.when(division);
    }
    var url = this.fooApi + "current/Me?$select=CurrentDivision";
    return $http.get(url).then(function (data) {
         division = data.d.results[0].CurrentDivision;
         window.localStorage.setItem("CurrentDivision", division);
         return division;
    });
}