2016-07-10 163 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