【发布时间】:2021-12-22 07:48:54
【问题描述】:
我试图在我的数据库中插入一些东西,然后直接访问它,但由于节点是异步的,这在某种程度上无法按计划工作。但我知道必须有办法让这一切顺利进行。 这是我的代码:
router.post('/anzeigeerstellen', upload_inserat.single('Anzeigebild'), function (req, res) {
let titel = req.body.TitelderAnzeige,
beschreibung = req.body.Beschreibung,
inbild = req.file.filename,
ses = req.session;
pool.query("INSERT INTO inserat (titel, beschreibung, inseratbildname, email)
VALUES (?, ?, ?, ?)",
[titel, beschreibung, inbild, ses.email],
(error, results, fields) => {
pool.query("SELECT iid FROM inserat WHERE titel = ?, beschreibung = ?,
inseratbildname = ?, email = ?",
[titel, beschreibung, inbild, ses.email],
(error, results, fields) => {
res.redirect('anzeige?id=' + results[0].iid);
});
});
});
错误如下:
TypeError: Cannot read properties of undefined (reading '0')
我尝试过 async 和 await,但它对我不起作用(老实说,我也不确定我是否正确使用它)。
【问题讨论】:
-
我猜这与异步无关,您收到此错误是因为您的
results是undefined。你没有处理错误,所以不能保证你有正确的结果(或根本没有) -
是的,但我如何才能确保 INSERT 在 SELECT 之前发生?那么就没有可能的错误了,但我还是会做错误处理,以防万一...... :) THX!
标签: javascript mysql sql node.js express