AngularJS TypeError:无法读取属性'然后'未定义的

时间:2015-07-27 16:59:09

标签: javascript angularjs angular-promise

我在AbgularJS服务中有以下功能:

var readFile = function (path, file) {
            console.info("Trying to read file with URI: " +path+ " "+file);
            $cordovaFile.checkFile(path, file).then(function (success) {
                console.log(success);
                var deferred = $q.defer();
                $cordovaFile.readAsText(path, file)
                    .then(function (success) {
                        // success
                        console.log("Success");
                        console.log(success);
                        deferred.resolve(success);
                    }, function (error) {
                        console.error(error);
                        deferred.reject(error);
                    });
                return deferred.promise;
            }, function (error) {
                console.log(error);
            });
        }
成功回调中的

是文件读取的定义函数。

但我总是在这个地方收到异常消息:

TypeError: Cannot read property 'then' of undefined

但如果我这样做:

$cordovaFile.checkFile(path, file).then(function (success) {
                console.log(success);

            }, function (error) {
                console.log(error);
            });

它工作正常。

我想只在文件存在的情况下执行文件读取,但我不知道以正确的方式做到这一点。

通过这种方式调用服务方法:

DeviceSrv.readFile(cordova.file.externalRootDirectory+"/"+APP_CONST.MP3_FOLDER_NAME+"/sounds/", APP_CONST.MP3_FILE_NAME)
                .then(function(value){
                    console.log(value);
                    var parsedObject = JSON.parse(value);
                    console.log(parsedObject);
                    $scope.availableSounds = parsedObject.availableSounds;
                    $scope.availablePrepreparedSounds = parsedObject.availablePrepreparedSounds;
                });

我应该如何更新代码以正确的方式执行代码?

非常感谢您的任何建议。

1 个答案:

答案 0 :(得分:0)

由于promises可以链接,你只需返回整个promise,而无需创建deferred。

   var readFile = function (path, file) {
    console.info("Trying to read file with URI: " +path+ " "+file);
    return $cordovaFile.checkFile(path, file).then(function (success) {
        return $cordovaFile.readAsText(path, file);
     }).then(function (success) {
           // success
           console.log("Success");
           console.log(success);
      }).catch(function (error) {
           console.error(error);               
      });
  }
相关问题