如何在角度中掌握这个条件承诺?

时间:2016-09-26 19:03:20

标签: javascript angularjs

我必须在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,则需要等待或继续。

2 个答案:

答案 0 :(得分:1)

如果您只需要一个api电话:使用$ 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);
});

答案 1 :(得分:0)

从angular使用'then',这样一旦解决了promise,你就可以检查promise中返回的数据并执行你的逻辑