0

I must solve a problem in angularjs and I'm stuck for some hours right now.

if have this pseudo code:

doSomething(param){

    var res;
    if(param = "ok"){
        //do some api calls with promise
        res = promise result
     }

    doSomeStuff(){
        //if i got res variable, continue with this...
        // else
        //if res is not set, do this...
    }

So my question is: How i can do something like this? The doSomeStuff function needs to know, if variable res is set or not. So it needs to wait, or to continue, if the variable res is not set.

CDspace
  • 2,639
  • 18
  • 30
  • 36
  • 1
    Put the `doSomeStuff` code in the `then` of your promise. Remove the `res` variable and the promise itself should return a set/unset value, which you can use to branch within `doSomeStuff`. – nem035 Sep 26 '16 at 19:07
  • Possible duplicate of [JavaScript isset() equivalent](http://stackoverflow.com/questions/2281633/javascript-isset-equivalent) – Mehrad Sep 26 '16 at 19:08
  • @darham hardly a duplicate of that question. This question involves asynchrony as well. – nem035 Sep 26 '16 at 19:09

2 Answers2

1

If you need only one api call : use the then() of the $http

doSomething(param){
    if(param == "ok"){
        //do some api calls with promise
        $http({
           method: 'GET',
           url: url
        }).then(
           function success(response) {
                doSomeStuff(response);
           },
           function error(response) {
              console.log(response);
           }
        );
    }      
}

If you need to make many APi calls :

var doSomething = function (param){
    if(param == "ok"){
       // imagine that listeUrl is an array of url for api calls   
       var promises = [];
       for (var i in listeUrl ) {

          promises.push( //Push the promises into an array
              $http({
                 method: 'GET',
                 url: listeUrl[i]
              }).then(function success(response) {
                 return response.data;
              })
          );
       }
       return $q.all(promises); // Resolve all promises before going to the next .then
    }      
}

doSomething("ok").then(function(res){
    doSomeStuff(res);
});
AlainIb
  • 4,544
  • 4
  • 38
  • 64
  • note that `if(param = "ok")` is not a comparison but an assignment – charlietfl Sep 26 '16 at 19:25
  • thank you for your answers... but.. in the " doSomeStuff() " there is an " if/else " depends on the " res " variable.. so the solution from @AlainIb is not really what i need... or do i understand it wrong? – IsabelleDiez Sep 26 '16 at 19:52
  • you barely didn't provide anything to help us ... i edit the answers, just pass the response to your function, and inside it test the value like you want. – AlainIb Sep 26 '16 at 20:19
0

Use 'then' from angular so that once promise is resolved you can check the data returned from promise and perform your logic

Yogesh
  • 354
  • 2
  • 15