I'm working on my first Node app, and I'm having a weird issue. Basically, I'm calling function search with boolean parameter advancedMode determining what method search should call next. For some reason, this only works when advancedmode === false. When set to true, I get UnhandledPromiseRejectionWarning: TypeError: advancedSearch is not a function. For testing purposes, I've made the first line of each method (simpleSearch and advancedSearch a console.log. Relevant parts (truncated):api.js:async function search(request, advancedMode) { ... if (advancedMode) advancedSearch(request); else simpleSearch(request); ... } async function simpleSearch(request) { console.log("Performing simple search..."); ... } async function advancedSearch(request) { console.log("Performing advanced search..."); ... } module.exports = { router: router, search: search }; app.js:const api = require('./routes/api'); app.use('/api', api.router); app.post('/search', function(req, res) { let request = { name: req.body.name; city: req.body.city; } api.search(request, false); return; } app.post('/search/advanced', function(req, res) { let request = { firstname: req.body.firstname; lastname: req.body.lastname; ... city: req.body.city; } api.search(request, true); return; } Obviously, everything works up until this part: if (advancedMode) advancedSearch(request); else simpleSearch(request); If advancedMode is true at this point, I get the error referenced above. And I'm really struggling to understand why that is since the function declarations are pretty much identical, and they're called from the same function. What makes one callable and the other not?EDIT: SOLVEDI figured it out. Looking closer, I found that VSCode was reporting that function advancedSearch was never used. The simple explanation is that within the search method, I named the advancedMode parameter advancedSearch. I only decided to change it in my example code above to make it more readable.So at the point I try to call the method advancedSearch, the name is a reference to a boolean variable. Typing all of this out helped me realize that, though - so thanks! Gonna leave this up for anyone who might run into a similar issue.Also - another lesson here is don't change your code too much before asking for help. The small act of renaming a variable actually solved my problem so the code I'm asking you to troubleshoot is actually perfectly functional.Thanks for stopping by!
Submitted December 01, 2019 at 12:00PM by BillGoats
No comments:
Post a Comment