同步执行 Sequelize 查询

编程入门 行业动态 更新时间:2024-10-20 11:47:56
本文介绍了同步执行 Sequelize 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I am building a website using Node.js and Sequelize (with a Postgres backend). I have a query that returns many objects with a foreign key, and I want to pass to the view a list of the objects that the foreign key references.

在示例中,Attendances 包含 Hackathon 密钥,我想返回一个 Hackathon 列表.既然代码是异步的,那么下面的东西在Node中当然是行不通的:

In the example, Attendances contains Hackathon keys, and I want to return a list of hackathons. Since the code is async, the following thing of course does not work in 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}); });

有没有办法以同步方式进行该查询,这意味着我不会返回视图,直到我将hacks"列表填满所有对象?

Is there any way to do that query in a synchronous way, meaning that I don't return the view untill I have the "hacks" list filled with all the objects?

谢谢!

推荐答案

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

Use Promise.all to execute all of your queries then call the next function.

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 }); }) });

更多推荐

同步执行 Sequelize 查询

本文发布于:2023-10-26 23:39:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Sequelize

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!