首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >同步执行Sequelize查询

同步执行Sequelize查询
EN

Stack Overflow用户
提问于 2016-10-08 11:44:07
回答 2查看 9.6K关注 0票数 8

我正在建立一个网站使用Node.js和序列化(与Postgres后端)。我有一个查询,它返回许多具有外键的对象,并且我希望将外键引用的对象列表传递给视图。

在本例中,Attendances包含Hackathon键,我希望返回hackathons的列表。由于代码是异步的,因此以下内容在Node中当然不起作用:

代码语言:javascript
复制
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});
});

有没有办法以同步的方式进行查询,也就是说,直到"hacks“列表填满了所有的对象,我才会返回视图?

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-10-08 12:08:15

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

代码语言:javascript
复制
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
        });
      })
});

票数 7
EN

Stack Overflow用户

发布于 2021-04-12 12:07:47

在异步函数中使用for of

代码语言:javascript
复制
models.Attendance.findAll({
    where: {
        UserId: req.user.id
    }
}).then(async (data) => {

    let hacks = []

    for (const d of data) {

        const _hack = await models.Hackathon.findOne({
            where: {
                id: data[d].id
            }
        })

        hacks = [...hacks, _hack]
    }
    res.render('dashboard/index.ejs', {title: 'My Hackathons', user: req.user, hacks: hacks})
})

这将等待hacks数组在渲染之前被填满。这应该适用于API端点。

希望这篇文章能帮助任何遇到同样问题的人。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39928452

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档