我的问题涉及异步代码的使用。
以下是相关的伪代码:
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 循环中有一个conn.query()
(!result.done){}
但当然问题是conn.query()
代码异步运行,并且在下一次循环运行之前没有机会完成(导致 ~无限无目的循环)。
有第三方库方法可以让代码同步运行,但我的猜测是有一些我没有遵循的基本设计范式。 递归有效,但我担心如果查询返回大量 # 条记录可能需要的内存量。
即使我知道我需要分页的记录#,我也必须有分页result.nextRecordsUrl
,直到执行每个先前的查询我才能获得...所以我不能同时运行它们。
有人愿意对此进行权衡吗?
谢谢!
使用异步.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);
}
}
});
}
});
});
我根本不会那样做。 当你得到更大的数据集时,它的效率非常低。 相反,我会采用查询字符串参数,这些参数指示我想要开始的记录索引和要返回的计数。 所有数据库都有一个等价的 skip and take(例如,如果你使用 jsforce 方法链 API,你可以执行 .skip(5).take(10) 来返回集合中的记录 6 - 16)。 这大大简化了您的代码,并通过使每个请求独立于其他请求来降低风险。
另外,我注意到评论//(below code runs first when launched of course)
,但这也不是一个好主意。 理想情况下,您希望按需查询数据库,而不是在应用程序启动时查询数据库。这也可能是您遇到挑战的原因。
Hii 如果你使用的是 mongo db,那么试试这个。
user.aggregate({ $match: { status: true, type: req.query.type } },
{ "$skip": (skipValue) }, { "$limit": limitValue },
(err, data) => {
//Code
})