NodeJs:有没有办法退出整个函数,而不仅仅是返回内部函数?
所以我有这个函数
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不直接。当您的
run
回调运行时,调用它的函数已返回。这是因为 JavaScript 的运行到完成语义的本质以及这种 Node.js 回调是异步调用的事实。您可能会考虑在这些函数周围使用 Promise 包装器,然后将逻辑放入
async
函数中,以便您可以使函数的逻辑等到run
操作和您的处理其结果已完成。对于如此零碎的代码,很难给你一个具体的建议,但模糊是这样的: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 therun
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: