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.
CodePudding user response:
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...