After inserting a row into mysql, I am trying to retrieve the row ID.
con.query('INSERT INTO terminals SET ?', {title: 'test'}, function (err, result, fields) {
console.log(result.insertId);
});
Now I am trying to access result.insertId outside of the function. How is this possbile using async/await?
This didn't work for me:
const response = await con.query('INSERT INTO terminals SET ?', {title: 'test'}, async function (err, result, fields) {
return result;
});
console.log(await response.insertId);
you can create a function that will return a promise.
for example:
function asynqQuery(query, params) {
return new Promise((resolve, reject) =>{
con.query(query, params, (err, result) => {
if (err)
return reject(err);
resolve(result);
});
});
}
try {
const response = await asynqQuery('INSERT INTO terminals SET ?', {title: 'test'});
console.log(response.insertId);
} catch (e) {
console.error
}
Or you can try using "promisify" from the "util" library.
Try with this:
response[0].insertId
in:
const response = await con.query('INSERT INTO terminals SET ?', {title: 'test'}, async function (err, result, fields) {
return result;
});
console.log(response[0].insertId);
Result are always an array almost it have only 1 element
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.