当你说
在单个路由器下
我假设您的设置类似于 Node.js 和 Express.js 应用程序,其中您的路由和处理程序如下所示:
app.post('/delete', function (req, res) {
// delete some items from database
})
在这种情况下,您可以执行以下操作:
function deleteItems(req, res) {
// since Sequelize `destroy` calls return promises,
// you can just wrap all of them in `Promise.all`
// and "wait" for all of them to `resolve` (complete)
const handleSuccessfulDeletion = () => {
res.status(200).json({
status: 200,
message: 'OK'
})
}
const handleError = (error) => {
// ...
}
Promise.all([
deleteFromTable1(param1, transaction),
deleteFromTable2(param1, transaction),
deleteFromTable3(param1, transaction)
])
.then(handleSuccessfulDeletion)
.catch(handleError)
}
app.post('/delete', deleteItems)
这样,所有删除调用都会在您返回 success 响应之前完成。
或者,如果您需要按顺序调用,则可以执行以下操作:
function deleteItems(req, res) {
const handleSuccessfulDeletion = () => {
// ...
}
const handleError = (error) => {
// ...
}
deleteFromTable1(param1, transaction)
.then(() => deleteFromTable2(param1, transaction))
.then(() => deleteFromTable3(param1, transaction))
.then(handleSuccessfulDeletion)
.catch(handleError)
}
app.post('/delete', deleteItems)
这是一个例子 - jsbin.com