2016-07-10 165 views
0

我对此有点困惑。我在函数中有两个get调用。一旦这个完整的功能,那就是两个get调用完成了,只有这个功能完成了它的工作。我应该如何使用$ q来让它按照我的需要工作?这是我现在有:

function updateBlackList() { 
    $http.get("http://127.0.0.1:8000/blacklist/entries/vehicle").then(function (res){ 
     console.log(res)  
     }).catch(function (err) { 
     console.log(err) 
     }); 


    }) 
    $http.get("http://127.0.0.1:8000/blacklist/entries/person").then(function (res){ 
     console.log(res)  
     }).catch(function (err) { 
     console.log(err) 
     }); 


    }); 
    return $q.when(); 

    } 

这里withint另一个函数我需要等待上述fiunction完成:

BlackListService.updateBlackList().then(function() { 
       addVersion(server_version).then(function() { 
       console.log("Blacklist update complete") 
       }) 
      }) 

它没有这样做就像我怀疑它做的事。在TW GET请求完成

回答

3

要同时承诺在一个与$q.all()

function updateBlackList() { 
    return $q.all([ 
    $http.get("http://127.0.0.1:8000/blacklist/entries/vehicle") 
    .then(function (res){console.log(res)}) 
    .catch(function (err) {console.log(err)}), 

    $http.get("http://127.0.0.1:8000/blacklist/entries/person") 
    .then(function (res){console.log(res)}) 
    .catch(function (err) {console.log(err)}); 
    ]); 
} 

而且,你的第二个例子,你可以链的承诺结合起来,有一个更好看之前黑名单完整的控制台称为代码:

BlackListService.updateBlackList() 
.then(function() { 
    return addVersion(server_version); 
}) 
.then(function() { 
    console.log("Blacklist update complete"); 
}) 
+0

这很酷,谢谢你!我会记住 – Harry

2

使用$q.all

var VEHICLE_URL = "http://127.0.0.1:8000/blacklist/entries/vehicle"; 
var PERSON_URL = "http://127.0.0.1:8000/blacklist/entries/person"; 

function updateBlackList() { 
    var p1 = $http.get(VEHICLE_URL).then(whatever); 
    var p2 = $http.get(PERSON_URL).then(whatever); 

    return $q.all([p1, p2]); 
} 

updateBlackList() 
    .then(whateverElse); 
+0

不应该是'$ q.all([p1,p2])'? – rpadovani

+1

是的,谢谢你突出显示 – Ben

+0

好吧,我猜两个答案都是一样的,我喜欢变量beter – Harry