0

I have created a function to compress files to tar archive in a directory using tar module but I can't execute it with multiple functions through iteration because of its asynchronous behavior. How can I sync this function?

I've added sync: true to the options as it did on the documentation but it won't work

let fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isDirectory()) {
  tar
    .c({
        gzip: true,
        file: path.resolve(
          archivePath,
          file + " - " + date.getTime() + ".tar.gz"
        ), //compressed file name
        C: fullPath

      },

      ["."]
    )
    .then(() => {
      console.log({
        status: 0,
        message: "compressed - " + file
      });
    });
}
Clarity
  • 10,730
  • 2
  • 25
  • 35
  • You can wrap this in a promise, resolve inside `tar.c().then()` and then return that promise, then do `Promise.all` outside the iteration, adding each promise to `all` and doing `Promise.all().then()`. But if you want each iteration to start and end consecutively (potentially jeopardising performance), you have to chain each step instead of looping, a recursive should do with maybe `async/await`. – Abana Clara Aug 27 '19 at 10:59
  • could you explain more with a code it would be helpful – Pavan Vidusankha Aug 29 '19 at 06:17

1 Answers1

-1

tar is async so your loop didn't wait for lunch the next iteration ...

Add 'await' keyword front of tar command ...

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();
Andrelec1
  • 363
  • 4
  • 20