gpt4 book ai didi

node.js - 在 Sequelize 事务中执行 promise 列表时无法捕获/抛出错误?

转载 作者:行者123 更新时间:2023-12-03 22:26:10 25 4
gpt4 key购买 nike

在下面的代码中,我试图 upsert 到用户记录。如果任一记录未能 upsert ,我希望两条记录都回滚。

在下面的代码中,我通过设置 user_id = null 强制第二条记录失败。但是,它仍然命中 thenreturn result; 。它不会捕获/抛出错误或回滚事务。我也在我的日志中看到了这个错误:

Unhandled rejection SequelizeValidationError: notNull Violation: User.user_id cannot be null
at Promise.all.then

async function submitUsers(users) {
return db.sequelize.transaction(async (tx) => {
const queries = users.map((user, index) => {
if (index == 1) {
user.user_id = null;
}
User.upsert(user, tx);
});

await Promise.all(queries);
}).then((result) => {
return result;
}).catch((e) => {
throw e;
});
}


const users = [ {user_id: 1}, {user_id: 2}];
await submitUsers(users);

最佳答案

你没有正确地返回你的 promise 。试试这个;

async function submitUsers(users) {
return db.sequelize.transaction((tx) => {
const queries = users.map((user, index) => {
if (index == 1) {
user.user_id = null;
}
return User.upsert(user, tx);
});

return Promise.all(queries);
}).then((result) => {
return result;
}).catch((e) => {
throw e;
});
}

关于node.js - 在 Sequelize 事务中执行 promise 列表时无法捕获/抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60153511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com