0

I need to do a truncate of a table and then wait to start populate again, I must implement async/await otherwise is not working good.

How can I do this? I try with await on truncateCharfileWorldSaveTable and using async on that function but I don't understand how to make it work.

async function truncateCharfileWorldSaveTable(){
    let query = 'TRUNCATE charfiles_worldsave'

    await db.get().query(query, function (err, result, fields) {
        if (err) console.error('function truncateCharfileWorldSaveTable: ' + err);
        console.info('Tabla charfiles_worldsave_temporal TRUNCATE');
    });
}

exports.backupCharfiles = async function(req, res) {
    try {

        //Primero borramos todo el contenido de la tabla e iniciamos el proceso
        await truncateCharfileWorldSaveTable()

        console.info('==== INICIANDO COPIA DE CHARFILES POR WORLDSAVE ======')
        let files = fs.readdirSync('./charfiles/');
        files = files.filter(file => file.endsWith('.chr'));
        files.forEach(writeCharfileWorldSaveTable)
        res.status(200).send('Se estan guardando los charfiles en la base de datos');

    } catch(err) {
        console.error('function backupCharfiles: ' + err)
    }
};
1
  • Don't use callback APIs with promises. It's unknown what lib you're using for mysql but there are promise-based libs for it. Commented May 3, 2019 at 14:36

1 Answer 1

1

awaiting a function that takes callbacks does nothing. await needs a promise to work, and if you want to convert a callback-based function to Promise style function util.promisfy might help here.

However, there's also the mysql2 package, which is pretty great. You can require mysql2/promise instead of mysql which will turn all callback-based functions into awaitable promise-style functions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.