Skip to content
Advertisement

Then Vs Await issue

You dont have to read the code, what is happening is a file is being uploaded 1000 bytes at a time. And to ensure that we send the bytes in order we are using await. What if I wanted to use .then(), it seems hard as there is a loop around the fetch call.

        const fileReader = new FileReader();
        const theFile = f.files[0];
        fileReader.onload = async (ev) => {
          const CHUNK_SIZE = 5000;
          const chunkCount = ev.target.result.byteLength / CHUNK_SIZE;

          console.log("Read successfully");
          const fileName = Math.random() * 1000 + theFile.name;
          for (let chunkId = 0; chunkId < chunkCount + 1; chunkId++) {
            const chunk = ev.target.result.slice(
              chunkId * CHUNK_SIZE,
              chunkId * CHUNK_SIZE + CHUNK_SIZE
            );
            await fetch("http://localhost:8080/upload", {
              method: "POST",
              headers: {
                "content-type": "application/octet-stream",
                "content-length": chunk.length,
                "file-name": fileName,
              },
              body: chunk,
            });
            divOutput.textContent =
              Math.round((chunkId * 100) / chunkCount, 0) + "%";
          }
          console.log(ev.target.result.byteLength);
        };
        fileReader.readAsArrayBuffer(theFile);
      });

Advertisement

Answer

Here is the same functionality without await. It replaces the for loop:

const uploadChunk = (chunkId = 0) => {
  const chunk = ev.target.result.slice(
    chunkId * CHUNK_SIZE,
    chunkId * CHUNK_SIZE + CHUNK_SIZE
  );
  fetch("http://localhost:8080/upload", {
    method: "POST",
    headers: {
      "content-type": "application/octet-stream",
      "content-length": chunk.length,
      "file-name": fileName,
    },
    body: chunk,
  }).then(() => {
    divOutput.textContent =
      Math.round((chunkId * 100) / chunkCount, 0) + "%";
    (chunkId <= chunkCount) && uploadChunk(chunkId + 1);
  });
}

uploadChunk();
Advertisement