2016-09-26 56 views
0

我必须解决angularjs中的一个问题,并且我现在停留了几个小时。如何在角度上掌握这种有条件的承诺?

,如果有这样的伪代码:

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... 
    } 

所以我的问题是:我怎么能这样做? doSomeStuff函数需要知道,如果变量res设置或不。因此,如果未设置变量res,则需要等待或继续。

+1

把'doSomeStuff'代码在'then'你的承诺。除去'res'变量,promise本身应该返回一个set/unset值,你可以使用它来在'doSomeStuff'中分支。 – nem035

+0

[JavaScript isset()等效]的可能的重复(http://stackoverflow.com/questions/2281633/javascript-isset-equivalent) – darham

+0

@darham几乎不是这个问题的重复。这个问题也涉及到异步。 – nem035

回答

0

从角度使用“然后”因此,一旦承诺得到解决,你可以检查数据的承诺回来,如果你只需要一个API调用执行你的逻辑

1

:使用$ HTTP的then()

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); 
      } 
     ); 
    }  
} 

如果您需要进行许多API调用:

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); 
}); 
+0

你需要做一个或多个API调用吗? – AlainIb

+0

请注意'if(param =“ok”)'不是一个比较,而是一个任务 – charlietfl

+0

@charlietfl哦是啊谢谢我复制粘贴太快 – AlainIb