Javascript 调试未处理的承诺拒绝
我已经写信给以下db查询,以获得具有特定偏移量的所有帖子:Javascript 调试未处理的承诺拒绝,javascript,node.js,promise,async-await,knex.js,Javascript,Node.js,Promise,Async Await,Knex.js,我已经写信给以下db查询,以获得具有特定偏移量的所有帖子: async function getPaginationPosts(start, size) { try { const posts = await knex("posts").select().where({ deleted: false, }).orderBy("createdAt").limit(size).offset(start) } catch (e)
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
}
但是,我收到了以下未处理的承诺拒绝
(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
有什么建议说明我做错了什么吗?
帖子的定义不正确。在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
}
}
或:
记录未处理拒绝的一种方便方法是添加如下所示的侦听器(通常在应用程序的入口点,即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
});
谢谢你或你的回复。我调整了我的功能。然而,我仍然得到了一个承诺。有什么建议我在这里做错了什么,以及如何正确调试这些类型的拒绝吗?提前谢谢!看起来第二个错误与getPaginationPosts
函数无关。与getPaginationPosts
一起调用的还有哪些函数?另外,确保标记为async
的所有函数代码都在try/catch
块中。检查每个异步函数。我讨厌节点>:-(((如果您使用大型应用程序,这会非常有帮助。
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
});