jszip wait for creation of zip before working with data

Viewed 649

Working on a nodejs implementation of JSZip to create a zip file in binary string format and store its value in a global variable however in spite of using async/await the zipstring is being printed before the zipping process is finished,

Here is my code so far:

const JSZip = require("jszip");
const zip = new JSZip();
let s="not yet done";
let zipstring = "";
async function dozipping() {
  zip.file("Hello.txt", "Hello World\n");
  zip.generateAsync({ type: "binarystring" })
     .then(function(content) {
       console.log("doing");
       zipstring = content;
     });
}
async function status() {
  console.log(s)
  await dozipping();
  console.log(zipstring)
  s = "done";
  console.log(s)
}
status(); 

Expected Output

not yet done
doing 
*zipstring value*
done

Output I am currently getting

not yet done
done

doing

I am new to node and working with jszip for the 1st time and the documentation is a little confusing, sorry in advance if the question is too trivial

2 Answers

This is because the .then from zip.generateAsync does not halt the execution. You are gonna need to use

zipstring = await zip.generateAsync(...);

Await halts the execution of an asynchronous function until the promise is resolved.

The reason you got nothing is promises are async and they are called once the async task is completed with the status as fulfilled or rejected. I have made some changes to it:

const zip = new JSZip();
let s="not yet done";
let zipstring = "";
async function dozipping(){
      zip.file("Hello.txt", "Hello World\n");
      try {
        console.log("doing");
        const response = await zip.generateAsync({type:"binarystring"});
        zipstring = response;
        return response;
      } catch (error) {
        console.error(error); 
      }  
}
async function status(){
   try {
    console.log(s)
    await dozipping();
    console.log(zipstring)
    s="done";
    console.log(s)
   } catch (error) {
     console.error(error);
   }
    
}
await status(); 

I would suggest you to first go through how promises work and how async\await should be used. They are just a syntactic sugar on it. I am attaching the link to through them.

Related