Sunday, 4 June 2017

Is there a way to synchronously wait for the completion of an asynchronous function in Javascript?

I have the following javascript code written to run in node.js:

const fs = require("fs");
const path = require("path");

var copy = function(paramSource, paramDestination, paramCallback) {
  if (fs.existsSync(paramDestination)) {
    return paramCallback("Destination Exists"); //TODO make formal error code
  } else {
    fs.lstat(paramSource, function(error, sourceStats) {
      if (error) {
        return paramCallback(error);
      } else {
        if (sourceStats.isDirectory()) {
          fs.readdir(paramSource, function(error, sourceContents) {
            if (error) {
              return paramCallback(error);
            } else {
              fs.mkdir(paramDestination, sourceStats.mode, function(error) {
                if (error) {
                  paramCallback(error);
                } else {
                  if (sourceContents.length > 0) {
                    sourceContents.forEach(function(sourceChild) {
                      copy(path.join(paramSource, sourceChild), path.join(paramDestination, sourceChild), paramCallback);
                    });
                  }
                  return paramCallback(null, paramDestination);
                }
              });
            }
          });
        } else {
          var sourceFile = fs.createReadStream(paramSource);
          var destinationFile = fs.createWriteStream(paramDestination); //TODO permissions
          sourceFile.on("error", function(error) {
            return paramCallback(error);
          });
          destinationFile.on("error", function(error) {
            return paramCallback(error);
          });
          sourceFile.on("close", function() {
            //return paramCallback(null, paramSource);
          });
          destinationFile.on("close", function() {
            return paramCallback(null, paramDestination);
          });
          sourceFile.pipe(destinationFile);
        }
      }
    });
  }
};

var entities = 0;

copy("/home/fatalkeystroke/testing/directory_01", "/home/fatalkeystroke/testing/directory_01_copy", function(error, name) {
  if (error) {
    console.log(error);
  } else {
    console.log(name);
    entities++;
  }
});

console.log("Copied " + entities + " entities.");
console.log("Program Done.");

It's a testing exerpt from an application I'm working on. I would like to keep the asynchronous nature of the copy() function, however I also want a way to know when the full copy is complete (as the code related to entities implies). The reasoning is because I want to be able to tell when it's done of course, but also implement a progress tracking capability.

Is there a way to synchronously wait for the completion of an asynchronous function in Javascript?



via FatalKeystroke

No comments:

Post a Comment