Can someone help me fix this async code. I want it to run synchronously because I don't yet understand asynchronous code. I beed to run long running function downloadFile that downloads a docx from google drive. The problem is it returns from downloadFile before and logs in this order (as you can see in console output below)
/ Terminal output indicating it returns from function before fully downloading
// Starting downloading file
// Finished downloading file
// END
// Functions I have
module.exports = {
download: async function (id) {
// ...
console.log("Starting downloading file");
await downloadFile(id, dest, jwtClient);
console.log("Finished downloading file");
},
}
async function downloadFile(fileId, dest, jwtClient) {
await drive.files
.export(
{
fileId: fileId,
mimeType:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
auth: jwtClient,
},
{
responseType: "stream",
}
)
.then(async function (response) {
await response.data
.on("error", (err) => {
console.log("ERROR: ", err);
})
.on("end", () => {
console.log("END");
})
.pipe(dest);
});
}