javascript - 同步执行 Sequelize 查询

标签 javascript node.js postgresql asynchronous sequelize.js

我正在使用 Node.js 和 Sequelize(带有 Postgres 后端)构建一个网站。我有一个返回许多带有外键的对象的查询,我想将外键引用的对象列表传递给 View 。

在示例中,Attendances 包含 Hackathon key ,我想返回一个 hackathons 列表。由于代码是异步的,所以下面的事情当然在 Node 中不起作用:

models.Attendance.findAll({
    where: {
        UserId: req.user.id
    }
}).then(function (data) {
    var hacks = [];
    for (var d in data) {
        models.Hackathon.findOne({
            where: {
                id: data[d].id
            }
        }).then(function (data1) {
            hacks.append(data1);
        });
    }
    res.render('dashboard/index.ejs', {title: 'My Hackathons', user: req.user, hacks: hacks});
});

有没有办法以同步方式执行该查询,这意味着我不会返回 View ,直到我拥有包含所有对象的“hacks”列表?

谢谢!

最佳答案

使用 Promise.all 执行所有查询,然后调用下一个函数。

models.Attendance.findAll({
    where: {
        UserId: req.user.id
    }
}).then(function (data) {
    // get an array of the data keys, (not sure if you need to do this)
    // it is unclear whether data is an object of users or an array. I assume
    // it's an object as you used a `for in` loop
    const keys = Object.keys(data)
    // map the data keys to [Promise(query), Promise(query), {...}]
    const hacks = keys.map((d) => {
      return models.Hackathon.findOne({
        where: {
          id: data[d].id
        }
      })
    })
    // user Promise.all to resolve all of the promises asynchronously
    Promise.all(hacks)
      // this will be called once all promises have resolved so
      // you can modify your data. it will be an array of the returned values
      .then((users) => {
        const [user1, user2, {...}] = users
        res.render('dashboard/index.ejs', {
          title: 'My Hackathons', 
          user: req.user, 
          hacks: users
        });
      })
});

关于javascript - 同步执行 Sequelize 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39928452/

相关文章:

node.js - Passport.js deserializeUser 如何解密哈希 session 数据?

没有模式表的 PostgreSQL 列表表

javascript - Vue.js/Vuex : How do I v-bind to a state value?

javascript - 导航下拉有圆 Angular 问题

javascript - 如何使用 css 按钮调用 javascript 函数?

sql - 从postgres中的路径中分离出文件名

ruby-on-rails - PostgreSQL AT TIME ZONE 使用 JOIN 表

javascript - 显示有关导出完整 RadGrid Telerik Web 组件的数据的 javascript 警报

node.js - lambda 边缘 "The Lambda function returned invalid json: The json output is not parsable."

node.js - Nodejs实时在线人数统计