2

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);
Leonard Niehaus
  • 500
  • 6
  • 16
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – nicholaswmin Dec 04 '19 at 12:56
  • @NikKyriakides it should :-) – RidgeA Dec 04 '19 at 12:59

2 Answers2

2

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.

1

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