return 在 .then 的承诺中 - AngularJS

return in .then of promise - AngularJS

我有问题...

我在 AngularJS (Angular) 中创建了一个 ClientService,它应该 return 一个 Client ID,但它总是 returns undefined.

var clients = [ ];
var API = Restangular.all('clients');

var clientsReq = API.getList(); // Call API and get Promise
var clients = clientsReq.$object; // For Displaying the Object in DOM later

this.get = {
  byId: function(id) {
    clientsReq.then(function() { // Wait for clientsReq to finish
      for(var i = 0; i < clients.length; i++) { // Iterate over clients
        if(clients[i].id === id) { // Check if clientID matches ID
          console.log(clients[i]); // Debug - IT LOGS THE CLIENT! (Working)

          return clients[i]; // Returns undefined (Not working)
        }
      }
    });
  }
};

这是调用服务的控制器:

$scope.client = ClientService.get.byId('123');
console.log($scope.client); // Returns undefined

我已经用 $q 尝试了另一种实现方式,但是那个很糟糕,我什至懒得在这里展示它,因为它肯定是错误的。我真的不知道这里的问题是什么,但我猜它与 clientsReq.then() 有关。我不知道如何等待 Promise 否则我在 Google/Whosebug 上没有找到任何关于它的信息。

希望你能帮助我! <3

您需要在 clientsReq.then()

之前添加 return 语句
this.get = {
  byId: function(id) {
    return clientsReq.then(function() { // Wait for clientsReq to finish
      for(var i = 0; i < clients.length; i++) { // Iterate over clients
        if(clients[i].id === id) { // Check if clientID matches ID
          console.log(clients[i]); // Debug - IT LOGS THE CLIENT! (Working)

          return clients[i]; // Returns undefined (Not working)
        }
      }
    });
  }
};

然后在你的控制器中

ClientService.get.byId('123').then(function(client){

    //here use client
    $scope.client = client;
});

记住这是一个异步调用,所以你应该 return 承诺不是纯值。

这是 $q

的版本
var clients = [];
var API = Restangular.all('clients');
var deferred = $q.defer(); // created promise object

var clientsReq = API.getList(); // Call API and get Promise
var clients = clientsReq.$object; // For Displaying the Object in DOM later

this.get = {
    byId: function(id) {
        clientsReq.then(function(data) {
            for (var i = 0; i < clients.length; i++) {
                if (clients[i].id === id) {
                    console.log(clients[i]);
                    return clients[i]; // Returns undefined (Not working)
                }
            }
            deferred.resolve(clients); //this will call success method of promise and return clients.
        }, function(error) {
            deferred.reject(error); //this will call error method of promise and return error 
        });
        return deferred.promise; //this will tell the callee method that i will return something
    }
};

控制器

ClientService.get.byId('123').then(function(data) { //success callback called when resolve promise
    $scope.client = data;
    console.log($scope.client);
}, function(error) { //error callback called when reject promise
    console.log(error);
});

希望对您有所帮助,谢谢。