[英]Implement async/await node.js and mysql
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. 我需要截断一个表,然后等待再次开始填充,我必须实现async / await,否则将无法正常工作。
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. 我尝试在
truncateCharfileWorldSaveTable
使用await并在该函数上使用async
,但是我不知道如何使其工作。
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)
}
};
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. await
需要一个承诺才能工作,如果要将基于回调的函数转换为Promise样式函数util.promisfy
可能会有所帮助。
However, there's also the mysql2
package, which is pretty great. 但是,还有
mysql2
软件包,它非常棒。 You can require mysql2/promise
instead of mysql
which will turn all callback-based functions into awaitable promise-style functions. 您可以要求使用
mysql2/promise
而不是mysql
,这样会将所有基于回调的函数转换为可等待的promise样式函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.