我有一个离子应用程序需要下载数据(分页),并将其插入数据库递归(如管道)。我正在用(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 –