gpt4 book ai didi

async-await - 使用 ES7 异步函数对 Sequelize 进行未处理的拒绝

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

获取 Sequelize.js 模型的 ValidationFailed 时出现此错误:

Unhandled rejection SequelizeValidationError: Validation error: The Login is not a valid email



但是只有在使用 ES7 async 函数时才会出现这种未处理的拒绝,请参阅以下代码:
export async function create (req, res) {
try {
res.json({ admin : await Admin.create(req.body) });
} catch (err) {
const message = {
Login : err.errors.map(error => error.message),
};
res.status(400).json({ error : 'ValidationFailed', message : message });
}
}

但是,当我使用 ES5 promise 格式时,它不会抛出异常。
export function create (req, res) {
Admin.create(req.body)
.then(admin => {
res.json({ admin : admin });
}, err => {
const message = {
Login : err.errors.map(error => error.message),
};
res.status(400).json({ error : 'ValidationFailed', message : message });
});
}

有任何想法吗?

最佳答案

要等待使用异步函数解析的 promise ,您需要使用 await 关键字。

export async function create (req, res) {
try {
await res.json({ admin : await Admin.create(req.body) });
// ^^^^ very important to include
} catch (err) {
const message = {
Login : err.errors.map(error => error.message),
};
res.status(400).json({ error : 'ValidationFailed', message : message });
}
}

如果没有 async 关键字,该错误不再在范围内,并成为未处理的异常。

关于async-await - 使用 ES7 异步函数对 Sequelize 进行未处理的拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31864122/

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