1

Here's a piece of code:

import fs from 'fs-extra'

async tackleZipFile() {
    let outputPath = `path/to/the/zip/file`;
    let output = fs.createWriteStream(outputPath);
    const readZipFile = new Promise((resolve, reject) => {
          output.on('close', resolve);
        })
    await readZipFile;

    // do something more
}

Now the code above runs OK. However, when I changed the readZipFile into something below, it went wrong:

const readZipFile = new Promise((resolve, reject) => {
          output.on('close', resolve());
        })

In the end I changed it into this, and it went well again:

const readZipFile = new Promise((resolve, reject) => {
          output.on('close', () => {
                resolve();
            });
        })

Why is the second implementation wrong? In my mind the second is the same with the third one: a function with no parameters passed into it. And why is the first implementation working? Can anyone explain the inner logic among these implementations?

Thank you.

Gary Yuan
  • 33
  • 2
  • 9
  • *"Why is the second implementation wrong?"* Because `output.on('close', resolve());` **calls** `resolve` and passes its return value into `output.on`, exactly the way `bar(foo())` **calls** `foo` and passes its return value into `bar`. If you need to pass an argument to `resolve`, your third approach is correct: wrap it in an arrow function and include whatever you're passing to it in the `resolve(/*...argument here...*/)` call. – T.J. Crowder May 07 '20 at 08:19

0 Answers0