我正在使用 Node/Express、Sequelize 和 MySQL,并尝试链接一些 promise 。
我有 Project
模型,并且通过 hasMany
关系,我有 ProjectImages
。我正在添加/更新特定项目 (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,
});
});
});
它有效,但我认为这有点像回调 hell 。
那么,有没有更好的方法来链接这个 promise ?
此外,这种在关联模型中添加/更新行的方式会创建大量查询。有更好的方法来完成这项任务吗?
最佳答案
好吧,你实际上并没有链接 promise ,而是嵌套它们。
正确的链接如下所示:
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,
});
});
您也可以查看async
/await
。
关于javascript - Sequelize 查询中正确的 promise 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51465294/