1 year ago
#386005
Nothere
Why is the code below 'return next()' still being executed?
As I understood next()
, it stops the middleware function and moves on (to the next middleware). Here, however the second then()-method is executed ignoring the next().
This leads to an error in my code, if the user already exists and nothing is inserted. Using just next() without return, didn't help.
function middlewareFunction(req, res, next) {
const id = req.body.id;
database.query("SELECT * FROM user WHERE id = ?", id)
.then(result => {
if(result.length) { // user is already stored in db
console.log("User already exists");
req.body.userId = result[0].id;
return next();
} else { // user isnt stored in db, storing user first time
console.log("User doens't exist yet, storing user.")
return database.query("INSERT INTO user (id) VALUES (?)", id)
}
})
.then(result => {
console.log("Insert result:", result);
req.body.userId = result.insertId;
console.log("User got id:", result.insertId);
return next();
})
}
The middleware should end when either the user exists(first next()) or the new user is inserted(second next()).
javascript
node.js
promise
middleware
0 Answers
Your Answer