Question
How to know when to use db.serialize()
?
Answer
Oftentimes we will have standalone queries that will only be triggered by a user’s request, for example, a login, the user fills in their info and clicks sign in, that click can trigger a query to search for the user that matches the username and password (hypothetically, passwords should not be stored in databases under no circumstance), if a match is found we let the user go to their profile. but what about when a request is more complicated, for example, if in a movie database a user wants to search for all action movies that have a rating greater than 4 stars, but we have two databases, one is movies, and the second is user ratings, so we would either, nest our query:
db.run("SELECT * FROM Movies ...", (err, rows)=> {
db.run("SELECT * FROM Ratings WHERE ....", (err, rows) => {
...
})
})
or we could serialize:
db.serialize(() => {
db.run("SELECT * FROM Movies ...", (err, rows)=> { ... });
db.run("SELECT * FROM Ratings WHERE ....", (err, rows) => { ... });
})
which we could use to assign the result of one of the queries to a variable and use it for the other.
There will be times when nesting might make more sense, but most commonly, serialize provides great support for multiple queries that either they are dependent of one another, or need to happen in certain order (like a table creation and seeding).