pouchDB allDocs returns 未定义

pouchDB allDocs returns undefined

我只想从数据库中获取前缀为 us:: 的用户文档。 当我 运行 下面的代码时,我得到 $scope.userList 未定义。 当我 console.log 在服务中时,我看到了对象数组。

我如何return数据?

$scope.usersList = $pouchDB.getAllDocs('us::');





.service("$pouchDB", ["$rootScope", "$q", function($rootScope, $q) {

.........
    this.getAllDocs= function(field){
            database.allDocs({
                  include_docs: true,
                  attachments: true,
                  startkey: field,
                  endkey: field && '\uffff'
            }).then(function (result) {

                console.log(result);
                return result;

            }).catch(function (err) {
                  console.log(err);
                  });
          };


...
}]);

这是异步代码与同步代码的问题。您不能编写 returnresult 的函数,因为 allDocs() 是异步的(基于承诺)。

我建议阅读 async code guide 以巩固您的理解。在 Angular 的情况下,您可能想要查看指南如何告诉您使用 $http 服务,该服务也是异步和基于承诺的。 IE。想象 PouchDB 是一个向您发送数据的远程 HTTP 服务器,然后围绕它构建您的应用程序。

我有一个使用 PouchDB 的开源 Angular 应用;在我的例子中,我使用了 Angular 服务。您可以查看代码以获取一些灵感:pouchService.js.

@nlawson 评论引导我回答,我研究了很多关于承诺的帖子,这对我有用。

非常感谢任何有助于改进我的编码的反馈!

在我的控制器中:

if ($stateParams.documentId) {
            $scope.inputForm = {};
            $scope.usersList = [];
            $pouchDB.get($stateParams.documentId).then(function (result) {
                result.woDate = new Date(result.woDate);
                $scope.inputForm = result;
                $scope.inputForm.prId = $stateParams.prId;
                return $pouchDB.getAllDocs('us::');
            }).then(function(udata){
                    $scope.usersList = udata.rows;
            }).catch(function (err) {
                    //do something with err
            });
        }

我的服务是

.service("$pouchDB", ["$rootScope", "$q", function($rootScope, $q) {
.....
     this.getAllDocs = function(field){
                var data;
                return database.allDocs({
                  include_docs: true,
                  attachments: true,
                  startkey: field,
                  endkey: field && '\uffff'});
      };
.....
}]);