[英]How do I best handle this pagination with asynchronous Node.js?
我的問題涉及異步代碼的使用。
這是相關的偽代碼:
function handleQueryMore(result) {
conn.queryMore(result.nextRecordsUrl, function(err, resultMore){
if (err) {}
//do stuff with result
if (!resultMore.done){
handleQueryMore(resultMore);
}
});
}
//(below code runs first when launched of course)
var conn = new jsforce.Connection({////etc
var sql = "SELECT //.......
conn.query(sql, function(err, result) {
if (err) {}
//do stuff with result
if (!result.done) //didn't pull all records
{
handleQueryMore(result);
}
});
初始查詢僅返回一定的最大記錄數,然后遞歸調用handleQueryMore()以處理每個額外的記錄塊。
最初,我在where (!result.done){}
循環中只有一個conn.query()
,但是當然問題是conn.query()
代碼異步運行,並且沒有機會在下一次循環(導致〜無限無目的循環)。
有第3方庫方法可以使代碼同步運行,但是我猜想我沒有遵循一些基本的設計范例。 遞歸有效,但是我擔心如果查詢返回大量的記錄,可能需要的內存量。
即使我知道需要分頁的記錄數,我也必須要有result.nextRecordsUrl
才能分頁,在執行每個先前的查詢之前,我無法獲得該分頁...因此,我不能只在同時。
有人在乎這個嗎?
謝謝!
使用async.js包。
function handleQueryMore(result) {
conn.queryMore(result.nextRecordsUrl, function(err, resultMore) {
if (err) {}
//do stuff with result
else {
async.each(result.data, function(individualData, callback) {
// do some async task
callback(); // to tell that this is completed
//callback(err); if there is any error while processing data
}, function(error) {
if (!error) {
if (!result.done) //didn't pull all records
{
handleQueryMore(result);
}
}
});
}
});
}
var conn = new jsforce.Connection({ ////etc
var sql = "SELECT //.......
conn.query(sql, function(err, result) {
if (err) {} else {
async.each(result.data, function(individualData, callback) {
// do some async task
callback(); // to tell that this is completed
//callback(err); if there is any error while processing data
}, function(error) {
if (!error) {
if (!result.done) //didn't pull all records
{
handleQueryMore(result);
}
}
});
}
});
});
我根本不會那樣做。 當您獲得更大的數據集時,效率極低。 取而代之的是,我將使用querystring參數,這些參數指示我要開始的記錄索引和要返回的計數。 所有數據庫都具有等效的跳過和獲取(例如,如果您使用的是jsforce方法鏈API,則可以執行.skip(5).take(10)以返回一組記錄6-16)。 通過使每個請求彼此獨立,這大大簡化了代碼並降低了風險。
另外,我注意到注釋//(below code runs first when launched of course)
, //(below code runs first when launched of course)
,但這也不是一個好主意。 理想情況下,您希望按需查詢數據庫,而不是在應用程序啟動時查詢。 這也可能就是您遇到挑戰的原因。
user.aggregate({ $match: { status: true, type: req.query.type } },
{ "$skip": (skipValue) }, { "$limit": limitValue },
(err, data) => {
//Code
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.