[英]How can make this code run synchronous in Node.Js?
我想使用EasyFTP移動文件,但是如果我關閉連接,則它在移動任何文件之前都會關閉,如果我不關閉連接,則會出現錯誤。
錯誤:首先需要503 RNFR
所以這是我的代碼
var EasyFtp = require('easy-ftp');
var ftp = new EasyFTP();
var config = {
host: '',
port: 21,
username: '',
password: ''
};
ftp.connect(config);
var filesFrom=['/file1.txt','/anotherFile.txt','/moreFiles.txt','/a.txt','/x.txt']
var filesTo=['/archived/file1.txt','/archived/anotherFile.txt','/archived/moreFiles.txt','/archived/a.txt','/archived/x.txt']
for (var i = 0; i < filesFrom.length; i++) {
ftp.mv(filesFrom[i], filesTo[i], function(err, newPath){
if (err) { console.log(err) }
});
};
ftp.close();
您無法使異步事物在Javascript中同步運行。 而且,由於for
循環是同步的,因此在進行下一次迭代之前,您不能讓for
循環等待異步操作完成。 因此,您必須為迭代使用其他技術。 有很多不同的選擇。 這是一個手動迭代的選項,在上一個完成后觸發下一個迭代:
function mvFiles(ftpObj, fromArray, toArray, callback) {
let index = 0;
let results = [];
function next() {
if (index < fromArray.length) {
let i = index++;
ftpObj.mv(fromArray[i], toArray[i], function(err, newPath) {
if (err) {
callback(err);
} else {
results[i] = newPath;
// run next iteration now
next();
}
});
} else {
// all done
callback(null, results);
}
}
// start first iteration
next();
}
用法:
ftp.connect(config);
var filesFrom =['/file1.txt','/anotherFile.txt','/moreFiles.txt','/a.txt','/x.txt'];
var filesTo =['/archived/file1.txt','/archived/anotherFile.txt','/archived/moreFiles.txt','/archived/a.txt','/archived/x.txt'];
mvFiles(ftp, filesFrom, filesTo, function(err, newPaths) {
ftp.close();
if (err) {
// process error here
} else {
// all done here
}
});
藍鳥很容易
var Bluebird = require('Bluebird');
var EasyFtp = require('easy-ftp');
var ftp = new EasyFTP();
var config = {
host: '',
port: 21,
username: '',
password: ''
};
// Promisifying adds Async after every method which represents the promise version of that method... you don't have to follow the callback method.
Bluebird.promisifyAll(ftp);
ftp.connect(config);
// push your promises into an array and then Promise.all() it... It will either complete fully or throw an error even if one fails.... All or nothing.
var promises = [];
var filesFrom=['/file1.txt','/anotherFile.txt','/moreFiles.txt','/a.txt','/x.txt']
var filesTo=['/archived/file1.txt','/archived/anotherFile.txt','/archived/moreFiles.txt','/archived/a.txt','/archived/x.txt']
for (var i = 0; i < filesFrom.length; i++) {
promises.push(ftp.mvAsync(filesFrom[i], filesTo[i]))
};
// Now promises array contains all the promises and they have started executing.
Bluebird.all(promises).then(function(results) {
// Results is an array of results from all the promises in order.
console.log(results);
// Close connection.
ftp.close();
}).catch(function(err) {
console.log(err);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.