0

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);
    });
}
qnsi
  • 370
  • 4
  • 14
  • You can't synchronously retrieve an asynchronous result. – T.J. Crowder Sep 01 '21 at 09:09
  • 1
    But the issue with the async code is that the `then` handler returns an immediately-fulfilled promise, before the download is complete. Instead, return a promise that isn't fulfilled until you see the `end` event: https://pastebin.com/dVJLD7Gp – T.J. Crowder Sep 01 '21 at 09:17

0 Answers0