【问题标题】:Promise in angular.js + node.js/electron doesn't workangular.js + node.js/electron 中的承诺不起作用
【发布时间】:2015-11-03 04:04:48
【问题描述】:

我在电子中使用 angular.js 和 node-orm 来与数据库通信。 Node-orm find/get 函数是异步的,所以我尝试使用 Promises 在服务中获取数据,如下所示:

app.service('SearchService', function($q) {
  this.title = function(token) {
    var deferred = $q.defer();
    Unit.find({}).where("unit_title LIKE ?", ['%'+token.toUpperCase()+'%']).run(function(err, results) {
      if (err) {
        return console.error('error running title query', err);}
      deferred.resolve(results);
    });
    return deferred.promise;
  }
});
app.controller("GreetController", function($scope, SearchService) {
  $scope.units = SearchService.title('test');
});

目标是在视图本身中对 Promise 进行角度转换。:

<div ng-controller="GreetController">
<ul>
    <li ng-repeat="unit in units">{{unit.title}}</li>
</ul>
</div>

但是它不起作用。我知道 Promises 解决了,因为我可以将它们记录到控制台并使用 Chromium 的开发工具查看值。

【问题讨论】:

    标签: javascript angularjs node.js electron


    【解决方案1】:

    Promise 仍然是异步操作,所以 title 方法返回一个 Promise 对象,而不是实际的 results。您需要使用 promise then-able API 来提供回调,当数据可用时将被调用:

    app.controller("GreetController", function($scope, SearchService) {
      SearchService.title('test').then(function(data) {
          $scope.units = data;
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      • 2017-12-06
      • 2017-08-06
      • 2017-04-29
      • 2015-08-06
      • 2016-06-07
      • 1970-01-01
      相关资源
      最近更新 更多