Ich habe den folgenden JavaScript-Code in node.js laufen geschrieben:Gibt es eine Möglichkeit synchron auf eine rekursive asynchrone Funktion in Javascript zu warten?
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.");
Es ist ein Test Auszug aus einer Anwendung arbeite ich an. Ich möchte den asynchronen Charakter der Funktion copy() beibehalten, möchte aber auch wissen, wann die vollständige Kopie vollständig ist (wie der Code im Zusammenhang mit entities
impliziert). Die Begründung ist, weil ich in der Lage sein will, zu sagen, wann es natürlich ist, aber auch eine Fortschrittsverfolgungsfähigkeit einzuführen.
Gibt es eine Möglichkeit synchron auf die Beendigung einer rekursiven asynchronen Funktion in Javascript zu warten?
Nein, aber async/await Syntax kann der Code erscheinen, als ob Sie sind. – pvg
Was meinen Sie mit "synchron auf die Fertigstellung einer asynchronen Funktion warten"? Ist das nicht der Zweck von 'paramCallback'? – guest271314
ein Moment dachte, und Sie würden erkennen, wie unmöglich das ist: p –