2017-08-08 95 views
0

所以我有一種情況,我需要執行一堆http調用,然後一旦完成,繼續進行下一步。

下面是這樣做的代碼,工作正常。

但是,我現在需要在每個http調用之間等待幾秒鐘。有沒有辦法在我目前的設置中超時,還是會涉及到很多重構?

如果需要,可以發佈更多的代碼。我曾嘗試在http調用中傳入超時配置,但是,它們仍然在同一時間被解僱。

任何建議將是偉大的。

代碼

var allThings = array.map(function(object) { 
    var singleThingPromise = getFile(object.id); 
    return singleThingPromise; 
}); 
$q.all(allThings).then(function() { 
    deferred.resolve('Finished'); 
}, function(error) { 
    deferred.reject(error); 
}); 

回答

1

而不是使用$q.all的,你可能要執行順序調用一個在以前的成功,可能與使用的$timeout。也許你可以建立一個遞歸函數。

事情是這樣的..

function performSequentialCalls (index) { 
    if(angular.isUndefined(array[index])) { 
    return; 
    } 
    getFile(array[index].id).then(function() { 
    $timeout(function() { 
     performSequentialCalls(index + 1) 
    }, 1000) // waiting 1 sec after each call 
    }) 
} 

進樣東西需要正確。假定array包含使用其執行API調用的對象,其中包含id。還假定您正在使用$http。如果使用$resource,則相應地添加$promise

希望有所幫助!

+0

乾杯!考慮到我上面的設置,我會怎麼稱呼它? – user2085143

+0

@ user2085143你可以在你想要啓動API調用的地方調用該函數。而且,如果你看到'angular.isUndefined ...'的'if'條件,你可以在那裏寫入一些代碼(在'return'之前),這是所有調用完成時都需要執行的代碼。 – tanmay

+0

非常感謝。一旦我有適當的時間,我會嘗試一下,如果它正在工作,則標記爲正確。 – user2085143

0
function getItemsWithDelay(index) { 
    getFile(object[index].id).then(()=>{ 
    setTimeout(()=>{ 
    if(index+1 > object.length) { return } 
    getItemsWithDelay(index+1) 
    }, 5000) 
}) 
} 

您可以連續通話

+0

根據我的設置,我會如何打電話? – user2085143