javascript - 在 Async/Await 中包装 FTP 请求
问题描述
我正在尝试执行 FTP 请求,等到文件下载完毕,然后关闭 FTP 模块。当这两个操作都完成后,列出目录的内容。目前,它正朝着相反的方向发展。
我已经将它们包装在异步中,并在 FTP 之前添加了等待。但是首先记录目录列表。可以发现异步函数中的错误吗?
(async function () {
await Ftp.get("document.txt", "document.txt", err => {
if (err) {
return console.error("There was an error retrieving the file.");
}
console.log("File copied successfully!");
Ftp.raw("quit", (err, data) => {
if (err) {
return console.error(err);
}
console.log("Bye!");
});
});
})()
// Read the content from the /tmp directory to check it's empty
fs.readdir("/", function (err, data) {
if (err) {
return console.error("There was an error listing the /tmp/ contents.");
}
console.log('Contents of tmp file above, after unlinking: ', data);
});
解决方案
首先,await 仅适用于 Promise,而 ftp.get 显然使用回调而不是 Promise。因此,您必须将 ftp.get 包装在一个承诺中。
其次,您的 fs.readdir 在 async 函数之外,因此它不会受到 await 的影响。如果你需要延迟它,那么你需要它在 async 函数中,在 await 语句之后。
所以放在一起看起来像这样:
(async function () {
await new Promise((resolve, reject) => {
Ftp.get("document.txt", "document.txt", err => {
if (err) {
reject("There was an error retrieving the file.")
return;
}
console.log("File copied successfully!");
Ftp.raw("quit", (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
})
});
fs.readdir("/", function (err, data) {
if (err) {
return console.error("There was an error listing the /tmp/ contents.");
}
console.log('Contents of tmp file above, after unlinking: ', data);
});
})()
推荐阅读
- node.js - Typescript 中的继承或注入
- java - Java - 使用音乐播放控制按钮
- angular - 在没有 Angular 附加库的情况下使用 IdentityServer4/5
- node.js - 如何在所有路线中添加护照js(本地策略)
- python - Python Threading:每个线程都有不同的开始
- java - 在 python 中使用 Antlr4.7 使用 JavaLexer 和 JavaParser 时遇到问题
- reactjs - 如何通过输入 id 从 e.target.files[0] 获取图像,以便我可以设置图像的状态,然后通过 axios 发布它
- asp.net - 如何在 Jenkins 上构建 .Net 应用程序?
- javascript - 我用console.log输出函数,没有调用函数的toStrinig方法,为什么?
- c# - 如何在 Windows 应用程序 C# 中使用凭据从 URL 下载文件