2015-04-03 98 views
1

我想在另一個地方調用urls,但不是所有的都在同一時間,但無論我怎麼嘗試,他們似乎都發生在同一時間。這是我現在所擁有的...陸續訪問網址

$http.get('/some/url/foo1') 
    .then($http.get('/some/url/foo2')) 
    .then($http.get('/some/url/foo3')) 
    .then($http.get('/some/url/foo4')) 
    .then($http.get('/some/url/foo5')) 
    .then($http.get('/some/url/foo6')) 
    .then($http.get('/some/url/foo7')) 
    .then($http.get('/some/url/foo8')) 
    .then($http.get('/some/url/foo9')) 
    .then($http.get('/some/url/foo10')) 
    .then($http.get('/some/url/foo11')) 
    .then($http.get('/some/url/foo12')) 
    .then($http.get('/some/url/foo13')) 
    .then($http.get('/some/url/foo14')); 

這些不能同時發生,當一個完成時,我希望下一個啓動。

編輯:我也試圖把get在這樣的功能,但他們仍然都被調用,同時

$http.get('/some/url/foo1') 
    .then(rebuildModel('foo2')) 
    .then(rebuildModel('foo3')) 
    .then(rebuildModel('foo4')) 
    .then(rebuildModel('foo5')) 
    .then(rebuildModel('foo6')) 
    .then(rebuildModel('foo7')) 
    .then(rebuildModel('foo8')) 
    .then(rebuildModel('foo9')) 
    .then(rebuildModel('foo10')) 
    .then(rebuildModel('foo11')) 
    .then(rebuildModel('foo12')) 
    .then(rebuildModel('foo13')) 
    .then(rebuildModel('foo14')); 

    function rebuildModel(modelName) { 
     return $http.get('/some/url/' + modelName); 
    } 

EDIT2:這個工作...我看到我做錯了什麼

function rebuildModel(modelName) { 
    return function() { 
     return $http.get('/some/url/' + modelName); 
    } 
} 
+2

,你還在「通話中」的功能,而不是提供了一個函數的定義。修復你的例子try:function rebuildModel(modelName){return function(){return $ http.get('url'+ modelName); }}; – pixelbits 2015-04-03 02:47:36

回答

1

您所做的鏈接不正確。它應該是這樣的:

$http.get('/some/url/foo1') 
    .then(function() { return $http.get('/some/url/foo2'); }) 
    .then(function() { return $http.get('/some/url/foo3');}) 

記住then功能也將返回一個承諾,這是由它的,成功和錯誤回調的返回值解決。

+0

嘗試過,看看我的更新,但它沒有奏效。 – CaffGeek 2015-04-03 02:31:17

+1

@CaffGeek,這個答案應該工作。如果通過「試過」你的意思是你的編輯,那麼區別在於在這種情況下,匿名函數被傳遞給'.then',而在你的情況下,'rebuildModel'函數被調用並且返回值(一個promise)通過 – 2015-04-03 02:42:40

+0

是的,又一次改變了功能,它似乎已經工作。謝謝,我知道我需要傳遞一個函數,而不是調用一個函數,但由於某種原因,我似乎無法正確編寫它。 – CaffGeek 2015-04-03 02:52:30

2

then方法需要一個成功回調函數的第一個參數:

$http.get('url').then(successCallback); 

successCallback必須是一個函數的定義,如:

$http.get('url').then(function() { ... }); 

如果提供$http.get()作爲參數:

$http.get('url').then($http.get('url')); 

您正在調用一個函數,然後將返回值(這是一個promise對象)作爲successCallback傳遞給then方法。

這種情況類似於以下較爲明顯的情況:

a. alert 
b. alert() 

首先是一個函數的定義,二是調用該函數。

我同意Chandermani的回答,它應該是正確的。如果它不工作,也許是檢查錯誤:在你的榜樣

$http.get('/some/url/foo1') 
    .then(function() { return $http.get('/some/url/foo2'); }) 
    .then(function() { return $http.get('/some/url/foo3');}, 
    function() { alert('something went wrong');});