5

I'm new at javascript and I've hit a wall hard here. I don't even think this is a Sequelize question and probably more so about javascript behavior.

I have this code:

sequelize.query(query).success( function(row){
            console.log(row);
    }
)

The var row returns the value(s) that I want, but I have no idea how to access them other than printing to the console. I've tried returning the value, but it isn't returned to where I expect it and I'm not sure where it goes. I want my row, but I don't know how to obtain it :(

2 Answers 2

7

Using Javascript on the server side like that requires that you use callbacks. You cannot "return" them like you want, you can however write a function to perform actions on the results.

sequelize.query(query).success(function(row) {
    // Here is where you do your stuff on row
    // End the process
    process.exit();
}

A more practical example, in an express route handler:

// Create a session
app.post("/login", function(req, res) {
    var username = req.body.username,
        password = req.body.password;
    // Obviously, do not inject this directly into the query in the real
    // world ---- VERY BAD.
    return sequelize
      .query("SELECT * FROM users WHERE username = '" + username + "'")
      .success(function(row) {
          // Also - 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 and plain text password example - for brevity.

Functions act as "closures" by storing references to any variable in the scope the function is defined in. In my above example, the correct res value is stored for reference per request by the callback I've supplied to sequelize. The direct benefit of this is that more requests can be handled while the query is running and once it's finished more code will be executed. If this wasn't the case, then your process (assuming Node.js) would wait for that one query to finish block all other requests. This is not desired. The callback style is such that your code can do what it needs and move on, waiting for important or processer heavy pieces to finish up and call a function once complete.

EDIT

The API for handling callbacks has changed since answering this question. Sequelize now returns a Promise from .query so changing .success to .then should be all you need to do.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your response! I might still be misunderstanding. I've added req.session.user to store the row data so that this information can be accessed outside the function, but outside the function it is still undefined. Ultimately I want to store this information as I want to display it on multiple pages, but it seems that I don't know how to go about doing this.
You cannot access the data from within this function in the scope it's defined in. The first thing you have to learn with server side Javascript is to stop thinking synchronously. Whatever code you have outside of the function needs to inside of the function along with the req.session assignment. Look at the example I gave you - I do not process information outside of the callback, I do it inside.
Would please provide the link to the documentation from which you've got this implementation?
I get the following : sequelize.query(...).success is not a function is this now deprecated?
This answer is from 2013, it's reasonable to assume API changes have taken place in that time. The question uses the .success method for handling the callback although if you look at current sequelize documentation you can clearly see a Promise is now returned which should give you the data you need to move forward. I would say, don't copy/paste code from StackOverflow, read it, understand what it's doing and then write the code you need and you might be able to avoid problems like this.
3

According to the changelog

Backwards compatibility changes:

Events support have been removed so using .on('success') or .success() is no longer supported. Try using .then() instead.

According this Raw queries documentation you will use something like this now:

sequelize.query("SELECT * FROM `users`", { type: sequelize.QueryTypes.SELECT})
    .then(function(users) {
        console.log(users);
    });

2 Comments

I'm not sure my answer is of no use anymore, my answer address the issue posted in the question which is not about an API change, while this answer is more of a comment on mine and not a direct answer to the question. And my question is not "accepted." The person asking the question never marked the answer accepted.
I am executing below but getting data with "Rowdatapacket" attached to every row from result set my var query = "CALL getdata(:pagenum)"; sequelize.query(query,{ replacements :{ pagenum :n, type : sequelize.QueryTypes.SELECT}}).then(function (results){ console.log(results); }).error(function(err){ }); how to remove "rowdatapacket"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.