javascriptnode.jsasync-awaitjszip

jszip wait for creation of zip before working with data


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


Solution

  • 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.