I'm struggling with an event handler in javascript, I'm trying to make things respond correctly with async / await.
The issue in the code below is with the file.on
event-- I'm struggling to promisify it correctly. Currently the checkSomething
method returns before the file.on
handler is finished, and so returnValue
is always false
.
I could use some advice and best practices.
What's a good way to go ensure returnValue
is checked / set in the handler before the value is returned? I've tried putting the await
keyword in front of the event handler, and in its callback function but that didn't work, and I'm basically scruffing along at this point and could use some tips. Thanks.
const axios = require('axios')
const fs = require('fs')
/*....*/
let isItChecked = await checkSomething()
async function checkSomething() {
let returnValue = false
const response = await axios.get('https://someUrl.com', {
responseType: 'stream'
})
const file = fs.createWriteStream('./localFile.txt')
response.data.pipe(file)
file.on('finish' () => {
performATask().then((result) => {
if (result == 'good') {
returnValue = true //need to make sure this is evaluated before returning
}
})
})
return returnValue
}