如何得到函数return的结果?

How to get function return result?

我正在开发一个如下所示的文件读取服务:

angular.factory('fileService', fileService);

function fileService($cordovaFile){
    var service = {
        readFile: readFile
    };

    return service;

    ///////////////

    function readFile(path, file){
        $cordovaFile.readAsText(path, file)
        .then(function (success) {
            console.log("read file success");
            console.log(success);
            return success;
        }, function (error) {
            alert("Fail to read file:"+error);
            console.log("Fail to read file");
            console.log(error);
            return false;
        });
    }
}

然后像这样使用它:

var data = fileService.readFile(cordova.file.dataDirectory,filename);
console.log(data) //return undefined

问题是无法 return 数据。我怎样才能取回数据 return?

您的问题是您实际上没有return读取 readFile 函数的任何结果。您正在 return 从您的回调函数中获取数据,但如果您想到它...结果会 return 发送到函数 readFile 本身,并且它保留在该函数中。您想要做的是 return 函数 readFile 的全部结果,然后在您使用它的控制器中解决承诺。这是代码:

angular.factory('fileService', fileService);

function fileService($cordovaFile){
        var service = {
        readFile: readFile
    };

    return service;

    function readFile(path, file){
        return $cordovaFile.readAsText(path, file);
    }
}

然后你像这样使用它:

var data = fileService.readFile(cordova.file.dataDirectory,filename);
data.then(function (success) {
        // Do whatever you need to do with the result
    }, function (error) {
       /// Handle errors
    });

一般来说,当您使用服务来实现某种使用承诺和 return 结果的功能时,您应该始终 return 可以在任何地方解析的承诺对象需要。 我强烈建议您阅读对 promise objects.

的精彩解释

你的函数 readFile returns 什么都没有,所以,首先你应该返回承诺:

function readFile(path, file) {
  return
    $cordovaFile.readAsText(path, file).then(function (success) {
      console.log('Read file success');
      console.log(success);
      return success;
    }, function (error) {
      alert('Fail to read file: ' + error);
      console.log('Fail to read file');
      console.log(error);
      return false;
    });
}

然后,如果您尝试像以前那样使用它,您将不会再得到 undefined,您将得到一个承诺。

但由于它是一个异步方法,您会得到该承诺仍然未决,您可能不希望这样,因为您需要承诺的已实现值。所以,你应该这样使用它:

fileService.readFile(cordova.file.dataDirectory, filename).then(function(data) {
  // use data here
});