我遇到了fs.writeFile()和Promise.all的问题。
我有一个脚本,从dropbox中获取文件,将其保存在服务器上,并将其发送到几个SFTP,以便他们可以使用它。我的问题是,我总是有一个我的承诺,抛出一个错误,说文件不存在。我怀疑aynscrhonous进程有问题,但我找不到我做错了什么。
我使用的是ssh2-sftp-client和fs包。
请在下面找到我的代码摘录:
//I just got the dropboxfile with promise
.then(function(data) {
myDownloadedFile = data.name
return new Promise((res,rej) => {
fs.writeFile(myDownloadedFile, data.fileBinary, 'binary', function (err) {
if (err) {
throw err
rej("file not saved")
} else {
log.info('File save : ' + data.name)
res()
}
})
})
})
//FTP sending
.then(function() {
return Promise.all([sendFiletoFTP(myConnection1, "partner1"), sendFiletoFTP(myConnection2, "partner2"), sendFiletoFTP(myConnection3, "partner3")])
})在sendFiletoFTP函数下面:
var sendFiletoFTP = function(FTPObj, myPartenaire) {
return new Promise((res,rej) => {
let sftp = new Client();
sftp.connect(FTPObj).then(() => {
return sftp.put(myDownloadedFile, myDownloadedFile)
})
.then((data) => {
sftp.end()
})
.then(() => {
log.info("OK pour " + myPartenaire + " : " + myDownloadedFile);
res()
})
.catch((error) => {
rej(error)
})
})
}我得到的错误是:错误:找不到文件,这是在sftp.put()操作期间触发的。
你知道哪里会出问题吗?
发布于 2017-02-09 06:14:48
注意:您的第一个代码片段似乎无缘无故地组合了箭头和常规函数!为什么不在适当的地方使用箭头函数
myDownloadedFile看起来是全局的(或者必须存在于包含两个代码片段的作用域中),所以在发送完成之前可能会有什么东西关闭它?
现在,通过将filename传递给sendFiletoFTP函数,您可以确保某些全局对象不会在异步事件完成之前被“破坏”--这就是我所怀疑的情况,但在没有看到所有相关代码的情况下,这只是一种猜测。在下面的代码中,第一个Promise被解析为data.name,不需要任何var,因为.then是启动FTP进程的名称的参数
重写第一个代码段,如下所示:
.then(data => new Promise((res,rej) =>
fs.writeFile(myDownloadedFile, data.fileBinary, 'binary', err => {
if (err) {
rej("file not saved");
} else {
log.info('File save : ' + data.name);
res(data.name);
}
})
))
//FTP sending
.then(filename => Promise.all([
sendFiletoFTP(myConnection1, "partner1", filename),
sendFiletoFTP(myConnection2, "partner2", filename),
sendFiletoFTP(myConnection3, "partner3", filename)
])
);客户端不需要新的Promise构造函数,因为sendFiletoFTP ().connect已经返回了promise。添加额外的参数,则函数变为
var sendFiletoFTP = function (FTPObj, myPartenaire, myDownloadedFile) {
return new Client().connect(FTPObj)
.then(() => sftp.put(myDownloadedFile, myDownloadedFile))
.then(data => sftp.end())
.then(() => log.info("OK pour " + myPartenaire + " : " + myDownloadedFile));
};https://stackoverflow.com/questions/42111101
复制相似问题