I have a series of callbacks and events, and need to follow a synchronous flow, but cannot figure out how to organize this to accomplish as such.
A simplified version of the problem and code is as follows
I have a list of zips on a server that I download to local filesystem
const zipFiles = // very very long list of downloadedFiles
for (let i = 0; i < zipFiles.length; i++) {
  await processZipForExtraction(zipFiles[i]);
}
I want this await to really behave and wait for all below async processing to finish
private async processZipForExtraction (file: Image): Promise<any> {
  return new Promise(async (resolve, reject) => {
    let writeStream = fs.createWriteStream(file.name);
    readStream.pipe(writeStream);
    writeStream.on('finish', () => {
      // open zips
      var zip = new StreamZip({
        file: './' + file.name,
        storeEntries: true
      });
      zip.on('ready', () => {
        console.log('All entries read');
        // this only means the below event got fired for each file, and I get a count
      });
      zip.on('entry', (entry) => {
        if (entry.name.endsWith('') {
          zip.stream(entry.name, (err, stream) => {
            if (err) reject(err);
            let uploadStream = this.uploadFromStream(name);
            uploadStream.on('success', async () => {
              // this also means this entry in the zip is "done"
            });
            stream.pipe(uploadStream)
          });
        }
        else {
          // this also means this entry in the zip is "done"
        }
      });
    }
  });
}
Now the difficult here is that I want to wait until each entry in the zip is "done". Sometimes there's an async stream event (if it succeeded in the zip), and sometimes there isn't. How can I re-organize the logic so wait for
- Download each zip
- View each zip entry
- If it matches, process and upload stream
- Once all entry are both processed AND successfully uploaded 4a. delete the zip 4b. resolve the original processZipForExtraction (so that only one zip is being processed at a time)
I have several thousand and they're multi-gig so I want to only download one, process, delete, then start on the next one...
I'm sure I can re-organize the logic to be able to await everything but I can't figure out where or how, since the zip.on 'entry' event then itself has another stream event watcher inside in which I need to wait for, and I don't know how many files are in the zip until the 'ready' event fires
Thanks in advance!
 
    