异步调用后返回数据的工厂

时间:2014-10-15 08:34:06

标签: javascript angularjs angular-services

我有一个服务(工厂)使用其他服务来获取数据。这样的事情:

factory('myFactory', function(anotherFactory) {

     var factoryObject = {};

     factoryObject.myMethod = () {

          var newObjectToReturn;

          // async call
          anotherFactory.get(id, function(data) {

              // do some processing
              newObjectToReturn = data; 
          });

          return newObjectToReturn;
     }
   return factoryObject;
});

现在,问题当然是,由于异步调用,factoryObject.myMethod()总是返回undefined,因为首先执行返回newObjectToReturn,而我不能简单地返回数据。有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:-1)

在回调中返回响应数据

工厂(' myFactory',function(anotherFactory){

 var factoryObject = {};

 factoryObject.myMethod = () {

      var newObjectToReturn;

      // async call
      anotherFactory.get(id, function(data) {

          // do some processing
          newObjectToReturn = data; 
      },function(response){
           return newObjectToReturn;
      });
 }

返回factoryObject; });