[英]Proper promises chaining in Sequelize query
I am working with node/Express, Sequelize and MySQL, and am trying to chain some promises. 我正在使用node / Express,Sequelize和MySQL,并试图实现一些承诺。
I have Project
model, and with a hasMany
relation I have ProjectImages
. 我有Project
模型,并且具有hasMany
关系,我有ProjectImages
。 I am adding/updating some rows in the images of a specific project ( chainedPromises
), and after this task is finished I want to return this project with all its images: 我正在添加/更新特定项目( chainedPromises
)的图像中的某些行,完成此任务后,我想返回此项目及其所有图像:
var chainedPromises = [];
// First resolve this group
data.ProjectImages.forEach((element) => {
chainedPromises.push(
models.ProjectImages.upsert(element, {
where: {
id: element.id,
},
})
);
});
Promise.all(chainedPromises)
.then((responses) => {
responses.map((response) => {
logJSON(response);
});
})
// Then look for the project and related models
.then(() => {
models.Projects.findById(req.params.id, {
include: [
{
model: models.ProjectImages,
},
],
})
// And return it
.then((result) => {
logJSON(result);
return res.send({
Project: result,
});
});
});
It works, but I think it is a bit like a callback hell. 它有效,但我认为它有点像回调地狱。
So, is there a better way to chain this promises? 那么,有没有更好的方法来实现这一承诺呢?
Also, this way of adding/updating rows in a associate model creates tons of queries. 同样,在关联模型中添加/更新行的这种方式会产生大量查询。 Is there a better way to do this task? 有更好的方法来执行此任务吗?
Well, you don't actually chain the promises but nest them. 好吧,您实际上并没有链接承诺,而是将其嵌套。
Proper chaining would look like this: 正确的链接如下所示:
Promise.all(chainedPromises)
.then((responses) => {
responses.map((response) => {
logJSON(response);
});
})
// Then look for the project and related models
.then(() => models.Projects.findById(req.params.id, {
include: [
{
model: models.ProjectImages,
},
],
}))
// And return it
.then((result) => {
logJSON(result);
return res.send({
Project: result,
});
});
You could alternatively also look into async
/ await
. 您也可以选择查看async
/ await
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.