在我的应用程序中,我有一个模型说它是Record
,并且Record
可能有多个可以上传到服务器的Attachment
。
通常,当使用附件
(文件)创建记录
时,我会先上传并保存文件,然后保存记录,如下所示:
function createOrUpdateInfo(req, res, next) {
var record = req.body;
var attachmentIds = (record.files || []).map(function (a) {
return a.id;
});
var attachmentFilter = {
where: {
id: {
$in: attachmentIds || []
}
}
};
DB.sequelize.transaction(function (t) {
var pro;
if (record.id) {
//update
//update the basic information first
return Record.update(record, {
where: {
id: req.params.id
}, transaction: t
}).then(function (num, infos) {
//find the record just saved.
return Record.findById(req.params.id).then(function (record) {
//find the attachmens which have been saved
return Attachment.findAll(attachmentFilter).then(function (atts) {
//update the record, create the association.
return record.setFiles(atts, {transaction: t});
});
})
});
} else {
//save
return Record.create(record, {transaction: t}).then(function (record) {
return Attachment.findAll(attachmentFilter).then(function (atts) {
return record.setFiles(atts, {transaction: t});
});
});
}
}).then(function (result) {
Util.sendJson(res, result)
}).catch(function (err) {
next({message: err.message, code: 500});
});
}
如图所示,创建或更新记录
时嵌套回调过多。
这个问题可以解决吗?
最佳答案
我稍微重新组织了你的代码。希望对您有所帮助。
function createOrUpdateInfo(req, res, next) {
var record = req.body;
var attachmentIds = (record.files || []).map(function (a) {
return a.id;
});
var attachmentFilter = {
where: {
id: {
$in: attachmentIds || []
}
}
};
DB.sequelize.transaction(function (t) {
var pro;
return (function () {
if (record.id) {
//update
//update the basic information first
return Record.update(record, {
where: {
id: req.params.id
}, transaction: t
}).then(function (num, infos) {
//find the record just saved.
return Record.findById(req.params.id);
});
} else {
//save
return Record.create(record, {transaction: t});
}
}()).then(function () {
//find the attachmens which have been saved
return Attachment.findAll(attachmentFilter);
}).then(function (atts) {
//update the record, create the association.
return record.setFiles(atts, {transaction: t});
});
}).then(function (result) {
Util.sendJson(res, result)
}).catch(function (err) {
next({message: err.message, code: 500});
});
}
关于node.js - 使用事务时的 Sequelize 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35892739/