简体   繁体   English

如何使用Sequelize和Javascript返回查询结果?

[英]How do I return the results of a query using Sequelize and Javascript?

I'm new at javascript and I've hit a wall hard here. 我是javascript的新手,我在这里遇到了困难。 I don't even think this is a Sequelize question and probably more so about javascript behavior. 我甚至不认为这是一个Sequelize问题,可能更多关于javascript行为。

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. var行返回我想要的值,但除了打印到控制台之外我不知道如何访问它们。 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 :( 我想要我的排,但我不知道如何获得它:(

Using Javascript on the server side like that requires that you use callbacks. 在服务器端使用Javascript就好了,这要求你使用回调。 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. 函数通过存储对定义函数的作用域中的任何变量的引用来充当“闭包”。在上面的示例中,正确的res值被存储以供我提供给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. 如果不是这种情况,那么您的进程(假设Node.js)将等待该一个查询完成阻止所有其他请求。 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. 自回答此问题以来,处理回调的API已发生变化。 Sequelize now returns a Promise from .query so changing .success to .then should be all you need to do. Sequelize现在返回一个Promise.query因此更改.success.then应该是所有你需要做的。

According to the changelog 根据更改日志

Backwards compatibility changes : 向后兼容性更改

Events support have been removed so using .on('success') or .success() is no longer supported. 事件支持已被删除,因此不再支持使用.on('success')或.success()。 Try using .then() instead. 尝试使用.then()代替。

According this Raw queries documentation you will use something like this now: 根据这个Raw查询文档,您现在将使用类似的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM