[英]how can i solve a throw issue in mysql?
I would like to resend again the (err) => { if (err) throw Error("error: insert client");我想再次发送 (err) => { if (err) throw Error("error: insert client"); }, in the function that call it but the try catch dont works, i should use a promise?
},在 function 中调用它但 try catch 不工作,我应该使用 promise? or a callback?
还是回调? because the function send mail its the same issue, and i think its more clear try to use the try catch like the first example, but im not sure.
因为 function 发送邮件是同样的问题,我认为它更清楚尝试像第一个示例一样使用 try catch,但我不确定。 thanks for the help.
谢谢您的帮助。
const somefunction = ( res, req ) => {
try
{
registerClient( 2, res.data);
sendMail( "user@gmail.com", "welcome" );
}
catch( e )
{ res.send( e ) }
}
const registerClient = (id, data) => {
const time = new Date();
const query =
"INSERT INTO clientes( name, lastname, date, fk_user, type ) " +
"VALUES ( ?, ?, ?, ?, 'client' )";
connection.query(
query,
[data.name, data.lastname, time, id, ],
(err) => {
if (err) throw Error("error: insert client");
}
);
};
i should use a promise?
我应该使用 promise 吗? or a callback?
还是回调?
Yes.是的。
The try/catch
block is sync, so it cannot catch an async throw. try/catch
块是同步的,因此它无法捕获异步抛出。
In your code:在你的代码中:
(err) => {
if (err) throw Error("error: insert client");
}
The error "remains" inside the arrow function and it does not bubble up because it is executed in async (after the I/O to the database).错误“保留”在箭头 function 内并且不会冒泡,因为它是异步执行的(在数据库 I/O 之后)。
Here a callback example you can play with:这里有一个你可以玩的回调例子:
const somefunction = (res, req) => {
registerClient(2, res.data, (err) => {
if (err) {
res.send(e)
} else {
sendMail('user@gmail.com', 'welcome') // fire and forget style (?)
res.send('done')
}
})
}
const registerClient = (id, data, cb) => {
const time = new Date()
const query =
'INSERT INTO clientes( name, lastname, date, fk_user, type ) ' +
"VALUES ( ?, ?, ?, ?, 'client' )"
connection.query(
query,
[data.name, data.lastname, time, id],
cb
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.