首页 > 解决方案 > 在 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);
});

标签: javascriptnode.jsasync-awaites6-promise

解决方案


首先,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);
  });
})()

推荐阅读