I have a database query (function) which is asynchronous, and as a result I need to use a callback function (no problem with that). However, in Node.js I need to make two separate queries in the same POST function. Both are asynchronous, so I'm having trouble on how to continue with the execution of the POST.
Goal:
- Validate form entries for malformations, etc.
- Check if username exists in db before saving (must be unique)
- Check if email exists in db before saving (must be unique)
- Save user if everything checks out, else throw some errors
Normally, I would have something like this (oversimplified):
postSearch = function(req, res, next) {
var searchCallback = function(err, results) {
// Do stuff with the results (render page, console log, whatever)
}
// This is the db query - async. Passes search results to callback
defaultSearch(input, searchCallback);
}
Which only has one async query, so only one callback. Normally I would just get the db results and render a page. Now I have to validate some form data, so my POST function looks something like this:
postUser = function(req, res, next) {
// Some static form validation (works, no issues)
var usernameExistsCallback = function(err, exists) {
// Does the username exist? True/false
}
// DB query - passes true or false to the callback
usernameExists(username, usernameExistsCallback);
var emailExistsCallback = function(err, exists) {
// Does the email exist? True/false
}
// DB query - passes true or false to the callback
emailExists(email, emailExistsCallback);
// Check if ALL validation constraints check out, implement error logic
}
The node-postgres module is async, and as a result the queries need callbacks (if I want to return any value, otherwise I can just run the query and disconnect). I have no problem executing both of those queries. I can console.log()
the correct results in the callbacks. But now I don't know how to access those results later on in my postUser
function.
I've read all about async JavaScript functions, but I've been scratching my head on this one for three hours now trying ridiculous things (like setting global variables [oh my!]) to no avail.
The results I need from these two queries are simply true
or false
. How can I organize this code to be able to use these results in the postUser
function? It seems to me that I need something like a third callback, but I have no clue how to implement something like that. Is it necessary for me to start using async? Would it be a good idea? Nothing in this application is super complex thus far, and I'd like to keep dependencies low <-> it makes sense.