NodeJs:有没有办法退出整个函数,而不仅仅是返回内部函数?

发布于 2025-01-11 07:36:19 字数 407 浏览 0 评论 0原文

所以我有这个函数

app.post('/assignment/loan', (req, res) => {

,在该函数内部我有这个函数,

db.run('SELECT loanable FROM book WHERE id=?',[bookID],(err,row)=>{

我使用 return 但它只退出内部函数并继续执行其余函数。我想阻止整个 post 函数进一步执行。有办法做到这一点吗?

编辑:完整代码在这里: https://pastebin.com/8TPThfpW

提前谢谢您。

So I have this function

app.post('/assignment/loan', (req, res) => {

And inside that function I have this function

db.run('SELECT loanable FROM book WHERE id=?',[bookID],(err,row)=>{

I use return but it only exits the internal function and keeps on going with the rest. I want to stop the whole post function from executing further. Is there a way to do that?

Edit: Full code here: https://pastebin.com/8TPThfpW

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风筝在阴天搁浅。 2025-01-18 07:36:19

不直接。当您的 run 回调运行时,调用它的函数已返回。这是因为 JavaScript 的运行到完成语义的本质以及这种 Node.js 回调是异步调用的事实。

您可能会考虑在这些函数周围使用 Promise 包装器,然后将逻辑放入 async 函数中,以便您可以使函数的逻辑等到 run 操作和您的处理其结果已完成。对于如此零碎的代码,很难给你一个具体的建议,但模糊是这样的:

// In an `async` function...
const res = await promiseEnabledAppPost('/assignment/loan');
const row = await promiseEnabledDBRun('SELECT loanable FROM book WHERE id=?',[bookID]);
// ...do something with `row`...
if (/* you don't want to continue with the `post` callback logic */ {
    return;
}
// ...continue the logic from the `post` callback...

Not directly. By the time your run callback is running, the function that called it has already returned. This is because of the nature of JavaScript's run-to-completion semantics and the fact that Node.js callbacks of this kind are called asynchronously.

You might consider using promise wrappers around those functions, and then putting your logic in an async function so that you can make the function's logic wait until the run operation and your handling of its results are complete. It's hard to give you a concrete suggestion with such fragmentary code to work from, but something vaguely like this:

// In an `async` function...
const res = await promiseEnabledAppPost('/assignment/loan');
const row = await promiseEnabledDBRun('SELECT loanable FROM book WHERE id=?',[bookID]);
// ...do something with `row`...
if (/* you don't want to continue with the `post` callback logic */ {
    return;
}
// ...continue the logic from the `post` callback...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文