javascript - node.js express nested callback in route -


getting error "could not locate bindings file"

trying search blog posting, lookup banner based on blog abbrev, write out

without banner lookup, works fine

think screwing callback can't find example

app.get("/posting/:id", function(req,res) {   var db = app.get('db');   var id = [req.params.id];   console.log(id);   db.run("select * postings id=$1",[1], function(err,posting) {     console.log(posting);     var choice = posting[0].choice;     var banner = banner_lookup(choice, function(err, banner) {       console.log(banner);        res.render("posting", {posting:posting[0], banner:banner});            });   });  }); function banner_lookup(abbrev) {   console.log("banner lookup");   (i=0;i++;i<banners.length) {     if (abbrev == banners[i].abbrev) {       console.log(banners[i]);       return (banners[i]);     }   }   return {"name":"","color":"#000"}; } var banners = [{"abbrev":"aaa","name":"newsletter a", "color":"#888888"}]; 

the problem lies in part of program. passing 2 arguments banner_lookup function - variable choice , callback function expect banner available after lookup

var banner = banner_lookup(choice, function(err, banner) {   console.log(banner);    res.render("posting", {posting:posting[0], banner:banner});        }); 

however actual function definition of banner_lookup accepts 1 named argument - choice. banner_lookup function calculates , returns banner value not being passed callback function expect to. have explicitly write functionality support callback functionality in banner_lookup

your code (with callback functionality) this

function banner_lookup(abbrev, callback) {    console.log("banner lookup");    var banneroutput = {"name":"","color":"#000"};    (i=0;i++;i<banners.length) {       if (abbrev == banners[i].abbrev) {           console.log(banners[i]);           banneroutput = banners[i];       }    }    if(typeof callback == "function") {        callback(null, banneroutput);    } else {        return banneroutput;    }  } 

the above method accepts callback parameter, , if defined function, passes output function else returns earlier.

tip 1 : don't need implement callback functionality if banner_lookup function doing simple tasks in sync. can write

   var banner = banner_lookup(choice);    console.log(banner); 

this banner have expected result.

tip 2 : , amit pointed out in comment, read sql injection attacks. make sure sanitize variables go making db query (you directly accepting id parameter route , passing db query can misused.


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -