我有一個離子應用程序需要下載數據(分頁),並將其插入數據庫遞歸(如管道)。我正在用(Angular's)$ q服務創建承諾。問題是,當我調用這個遞歸函數時,數據正在被下載並插入成功,但是內存使用量一直在增加,並且當promise鏈完全解析時,分配的內存仍然在使用中。如何在遞歸創建promise時避免內存泄漏?
這裏是我的遞歸函數:
// offset: last downloaded row count
// limit: row count to download at each page
// numRows: row count to download at all
function dowloadAndInsert(offset, limit, numRows) {
var deferred = $q.defer();
// Recursion step: We do not reached at the end of data
if((offset + limit) <= numRows) {
// Download the data
downloadData(offset, limit)
.then(function(response) {
// Insert the data
insertData(response)
.then(function(insertTime) {
// Recursion step
dowloadAndInsert(offset + limit, limit, numRows)
.then(function() {
deferred.resolve();
})
.catch(function(reason) {
deferred.reject(reason);
});
})
.catch(function(reason) {
deferred.reject(reason);
});
})
.catch(function(reason) {
deferred.reject(reason);
});
}
// Base case: We reached at the end of data
else {
var remainingRows = numRows % limit; // Means the last limit actually
// If exists, insert remaining rows
if(remainingRows !== 0) {
// Download the last piece of data
downloadData(offset, remainingRows)
.then(function(response) {
// Insert the last piece of data
insertData(response)
.then(function(insertTime) {
// Base case, successfully downloaded and inserted everything
deferred.resolve();
})
.catch(function(reason) {
deferred.reject(reason);
});
})
.catch(function(reason) {
deferred.reject(reason);
});
}
else {
// Base case, successfully downloaded and inserted everything
deferred.resolve();
}
}
return deferred.promise;
}
注:響應對象從downloadData功能未來是一個很大的數據時,它有時會包含100.000行18列。內存使用總量變成1GB。我在iPad Air 2上運行我的測試。
我在遞歸函數中使用大數據,因此我的問題與其他遞歸內存泄漏問題有點不同。
感謝。
可能重複[如何用遞歸JavaScript承諾來阻止內存泄漏?](http://stackoverflow.com/questions/15027192/how-do-i-stop-memory-leaks-with-recursive- javascript-promises) –
請在提問前進行搜索。複製品的標題與您的標題幾乎完全相同,當我搜索您的標題時,它具有作爲第二個標題的複製品(當然這個問題之後)。 –
神聖推遲反模式:O –