0

I need to wait for a promise resolution.

 function myFunction(myService, projectId) {
        var localdata;
        var myDataPromise = myService.getData(projectId);
        myDataPromise.then(function(result) {  
           localdata = result;
        });
        var someResult = someProcess(localdata); // I need to wait for promise resolution.
        return someResult;
    }

UPDATE

I try to clarify my question. I have the myService service with function which return promise:

var getData = function (projectId) {
        return projectResource.getProjectUser({ projectId: projectId }, function (result) {
            return result;
        }).$promise;
    };
Mediator
  • 14,951
  • 35
  • 113
  • 191

2 Answers2

1

You don't need a local variable ...

function myFunction(myService) {
    return myService.getData().then(function(result) {  
       return result;
    });
}

and your caller would be:

myFunction(myService).then(function(result){
    //you can be sure that result is fully computed here
    console.log("Your result " + result);
}) 
Mik378
  • 21,881
  • 15
  • 82
  • 180
  • Sorry, I tried to clarify my question. I need local var – Mediator Jul 19 '15 at 17:09
  • @Mediator It doesn't change anything to the solution. It's pretty strange to do `.$promise`. Never used it. You should prefer using `$q.defer()` and `defer.resolve(...)`. – Mik378 Jul 19 '15 at 17:11
  • You don't need `.then(function(result) { return result; });` either. Just omit that part. – Bergi Jul 19 '15 at 17:39
  • Indeed, it's for letting the way to compute the result before returns it. – Mik378 Jul 19 '15 at 17:40
  • 1
    @Mik378: That probably would be the [deferred antipattern](http://stackoverflow.com/q/23803743/1048572). If there is a `.$promise` available, use it, don't construct deferreds. – Bergi Jul 19 '15 at 17:40
  • Thanks, I don't understand your question =( It is my bad english. – Mediator Jul 19 '15 at 17:56
0

You don't want to return data from a promise!
You do want to return a promise in order to "continue" the chain.

The wait you are looking for is the callbacks you attach to the promise.

function myFunction($scope, myService) {
    var myDataPromise = myService.getData();

    myDataPromise.then(function(result) {  
       // this is the "wait" your looking for.. 
       $scope.data = result;
       console.log("data.name"+$scope.data.name);
    });

    return myDataPromise; // return the promise
}
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99