I am trying to write "robocopy / mir" as a function in Node.js and it seems that I cannot plunge into the head how to correctly execute several asynchronous functions in order.
Some background:
- The script runs on Windows, so I need to find a way to copy files, saving modification time and getting progress notifications.
- To solve this problem, I continued to work and wrote my copy function in .NET (calling it using Edge.js). This copy function simply returns a request to copy the Node message file. This thing works flawlessly.
To copy files in order, my first thought was this:
Object.keys(filesToCopy).forEach(function(key) {
var deferred = q.defer();
var payload = {
sourcePath: key,
destPath: filesToCopy[key],
progressCallback: progressCallback
};
console.log('Copying %s...', sourcePath);
copyFile(payload, deferred.makeNodeResolver());
deferred.promise.then(function(result) {
console.log('%s complete.', result);
}, function(err) {
console.error('Error: ', err.message);
});
promises.push(deferred.promise);
});
, ( ) , .NET, , , :
1%
2%
1%
2%
3%
3%
, , , , . , . , , , , . , !
: , , , Edge.js . , filesToCopy, - :
return filesToCopy.reduce(function(prev, curr) {
return prev.then(function() {
var deferred = q.defer();
copyFile(curr, function(err, result) {
deferred.resolve(result);
console.log('Completed %s', result);
});
return deferred.promise;
})
}, q());
, .