我已写入以下数据库查询以获取具有特定偏移量的所有帖子:
async function getPaginationPosts(start, size) {
try {
const posts = await knex("posts").select().where({
deleted: false,
}).orderBy("createdAt").limit(size).offset(start)
} catch (e) {
console.log(e.message)
console.log(e.stack)
}
return posts
}
但是,我收到了以下Unhandled Promise Rejection
(node:1824) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: posts is n
ot defined
(node:1824) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejection
s that are not handled will terminate the Node.js process with a non-zero exit code.
我的问题是我没有在控制台中获得有关错误的任何进一步信息。
您网站的任何建议:
提前感谢您的回复!
更新
我将我的功能改为:
async function getPaginationPosts(size, offset) {
try {
return await knex("posts").select().where({
deleted: false,
}).orderBy("createdAt").limit(size).offset(offset)
} catch (e) {
console.log(e.message)
console.log(e.stack)
return null
}
}
现在我收到以下异常:
(node:9096) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: start is n
ot defined
我的函数中没有使用变量start
。
有什么建议我在这里做错了吗?
答案 0 :(得分:7)
记录未处理拒绝的便捷方法 - 添加侦听器(通常在应用程序的入口点,即main.js),看起来像这样
process.on("unhandledRejection", (error) => {
console.error(error); // This prints error with stack included (as for normal errors)
throw error; // Following best practices re-throw error and let the process exit with error code
});
答案 1 :(得分:5)
posts
的定义不在正确的位置。在try/catch
块之外定义它们或从try
块返回结果:
async function getPaginationPosts(start, size) {
try {
return await knex("posts").select().where({
deleted: false,
}).orderBy("createdAt").limit(size).offset(start)
} catch (e) {
console.log(e.message)
console.log(e.stack)
return null
}
}
或者:
async function getPaginationPosts(start, size) {
let posts
try {
posts = await knex("posts").select().where({
deleted: false,
}).orderBy("createdAt").limit(size).offset(start)
} catch (e) {
console.log(e.message)
console.log(e.stack)
}
return posts
}