Soy nuevo en el nodo y me quedé con este problema. Aquí está el archivo: estoy ejecutando la función 'startProcess' y quiero ejecutar 'downloadFiles' y esperar hasta que se complete y guardar los archivos antes de ejecutar cualquier código después.
¿Este código siempre termina ejecutando 'runVideoUploadEngine' incluso antes de que se complete la descarga?
const downloadAndSaveFiles = async ({ url, dir }) => { try { https.get(url, (res) => { // File will be stored at this path console.log('dir: ', dir); var filePath = fs.createWriteStream(dir); res.pipe(filePath); filePath.on('finish', () => { filePath.close(); console.log('Download Completed'); }); }); return true; } catch (e) { console.log(e); throw e; } }; const downloadFiles = async ({ data }) => { try { mediaUrl = data.mediaUrl; thumbnailUrl = data.thumbnailUrl; const mediaExt = path.extname(mediaUrl); const thumbExt = path.extname(thumbnailUrl); mediaDir = `${__dirname}/temp/${'media'}${mediaExt}`; thumbDir = `${__dirname}/temp/${'thumb'}${thumbExt}`; await downloadAndSaveFiles({ url: mediaUrl, dir: mediaDir }); await downloadAndSaveFiles({ url: thumbnailUrl, dir: thumbDir }); return { mediaDir, thumbDir }; } catch (e) { console.log(e); throw e; } }; module.exports = { startProcess: async ({ message }) => { //check if message is proper data = JSON.parse(message.Body); //download video and thumbnail and store in temp. console.log('starting download..'); const { mediaDir, thumbDir } = await downloadFiles({ data }); console.log('dir:- ', mediaDir, thumbDir); pageAccessToken = 'myRandomToken'; _pageId = 'myRandomPageID'; console.log('running engine'); await runVideoUploadEngine({ pageAccessToken, _pageId, mediaDir, thumbDir }); //start videoUploadEngine //on success: delete video/thumbnail }, };¿Qué estoy haciendo mal?
downloadAndSaveFiles devuelve una promesa (porque la función es async ), pero esa promesa no "espera" a que https.get o fs.createWriteStream y, por lo tanto, ninguno de los códigos que llama a downloadAndSaveFiles puede "esperar" correctamente.
Si interactúa con las API de devolución de llamada, realmente no puede usar async/await . Tienes que crear la promesa manualmente. Por ejemplo:
const downloadAndSaveFiles = ({ url, dir }) => { return new Promise((resolve, reject) => { // TODO: Error handling https.get(url, (res) => { // File will be stored at this path console.log('dir: ', dir); var filePath = fs.createWriteStream(dir); filePath.on('finish', () => { filePath.close(); console.log('Download Completed'); resolve(); // resolve promise once everything is done }); res.pipe(filePath); }); }); };