i'm new @ javascript , i've hit wall hard here. don't think sequelize question , more javascript behavior.
i have code:
sequelize.query(query).success( function(row){ console.log(row); } )
the var row returns value(s) want, have no idea how access them other printing console. i've tried returning value, isn't returned expect , i'm not sure goes. want row, don't know how obtain :(
using javascript on server side requires use callbacks. cannot "return" them want, can write function perform actions on results.
sequelize.query(query).success(function(row) { // here stuff on row // end process process.exit(); }
a more practical example, in express route handler:
// create session app.post("/login", function(req, res) { var username = req.body.username, password = req.body.password; // obviously, not inject directly query in real // world ---- bad. return sequelize .query("select * users username = '" + username + "'") .success(function(row) { // - never store passwords in plain text if (row.password === password) { req.session.user = row; return res.json({success: true}); } else { return res.json({success: false, incorrect: true}); } }); });
ignore injection , plain text password example - brevity.
functions act "closures" storing references variable in scope function defined in. in above example, correct res
value stored reference per request callback i've supplied sequelize. direct benefit of more requests can handled while query running , once it's finished more code executed. if wasn't case, process (assuming node.js) wait 1 query finish block other requests. not desired. callback style such code can needs , move on, waiting important or processer heavy pieces finish , call function once complete.
edit
the api handling callbacks has changed since answering question. sequelize returns promise
.query
changing .success
.then
should need do.
Comments
Post a Comment