I am working with node/Express, Sequelize and MySQL, and am trying to chain some promises.
I have Project
model, and with a hasMany
relation I have 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:
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.