Database return in asynchronous function with await

Asked

Viewed 41 times

1

I have an asynchronous function that I need to use await in the return of the database to use this data later when doing the next insertion using the LAST_USER_ID() MYSQL, however, using the await he to the execution there and apparently stands expecting more results than he already has and does not proceed further.

When I don’t use await and put a setInterval() to call a function and make the next insertion everything happens as expected, otherwise it tries to execute before having the result of the previous.

Apparently the await expects more results than I’m expecting and never skips to the next part.

Could someone help me find where I’m going wrong?

Follow the code below:

function sqlquery(str, params) {
    return new Promise((resolve, reject) => {
        con.query(str, params, (err, result) => {
            if (err) reject(err);
            resolve(result);
        })
    })
}
async function tudo() {
    console.log(`\n> Registrando 1...\n`)
    await sqlquery("INSERT INTO `log` (`data`, `horainicio`) VALUES (CURRENT_DATE(), CURRENT_TIME());", function lastId(err, result) {
        if (err) throw err;
        idRegistro = result.insertId
        console.log(`\n> Registrado 1.\n`);
    });

    console.log("\n> Registrando 2...\n");
    await sqlquery(`UPDATE log SET horafim = CURRENT_TIME() WHERE idlog = ${idRegistro}`)
    console.log("\n> Registrado 2.\n");
}
tudo();

outworking

node mysql.js

> Registrando 1...


> Registrado 1.

1 answer

1


You are using a function of callback at the same time that uses await. There’s no need to do this, since you converted con.query using Promise in function sqlquery, not to mention that this one does not use callback, as you yourself specified in the parameters (str, params).

With the function sqlquery, it already returns the value of idRegistro simply making a let idRegistro = await sqlquery(...);.

I made a mock of your code and see how it behaves:

const con = { // esse mock seria semelhante a sua "con"
  query: (str, params, callback) => {
    let err, result = null;
    return callback(err, result);
  }
};

function sqlquery(str, params) { // voce converteu aqui e pode usar await no lugar de callback
  return new Promise((resolve, reject) => {
    con.query(str, params, (err, result) => {
      if (err) reject(err);
      resolve({ insertedId: 1 }); // retorna 1 só para exemplificar
    });
  });
}

async function tudo() {
  console.log(`\n> Registrando 1...\n`);

// await sqlquery("INSERT INTO `log` (`data`, `horainicio`) VALUES (CURRENT_DATE(), CURRENT_TIME());", function lastId(err, result) {
//   if (err) throw err;
//   idRegistro = result.insertId
//   console.log(`\n> Registrado 1.\n`);
// });

  // use await normalmente, ela vai lhe retornar o id.
  let idRegistro = await sqlquery("INSERT INTO `log` (`data`, `horainicio`) VALUES (CURRENT_DATE(), CURRENT_TIME());");
  console.log(`\n> Registrado 1.\n`);
  console.log(idRegistro); // agora que o await de cima acabou, vai aparecer 1

  console.log("\n> Registrando 2...\n");
  await sqlquery(`UPDATE log SET horafim = CURRENT_TIME() WHERE idlog = ${idRegistro}`); // faz a query com o idRegistro igual a 1 
  console.log("\n> Registrado 2.\n");
}

tudo();

Now to handle any error that will be released by if (err) reject(err);, just involve your code in try/catch and treats errors in the block catch.

const con = {
  query: (str, params, callback) => {
    let err, result = null;
    return callback(err, result);
  }
};

function sqlquery(str, params) {
  return new Promise((resolve, reject) => {
    con.query(str, params, (err, result) => {
      if (err) reject(err);
      resolve({ insertedId: 1 });
    });
  });
}

async function tudo() {
  try {
    console.log(`\n> Registrando 1...\n`);

    // await sqlquery("INSERT INTO `log` (`data`, `horainicio`) VALUES (CURRENT_DATE(), CURRENT_TIME());", function lastId(err, result) {
    //   if (err) throw err;
    //   idRegistro = result.insertId
    //   console.log(`\n> Registrado 1.\n`);
    // });

    let idRegistro = await sqlquery("INSERT INTO `log` (`data`, `horainicio`) VALUES (CURRENT_DATE(), CURRENT_TIME());");

    console.log(idRegistro);

    console.log("\n> Registrando 2...\n");
    await sqlquery(`UPDATE log SET horafim = CURRENT_TIME() WHERE idlog = ${idRegistro}`);
    console.log("\n> Registrado 2.\n");
  } catch (error) {
    console.log(error);
    // trata os erros aqui
  }
}

tudo();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.