在 Async/Await 中包装 FTP 请求

Wrap a FTP request in Async/Await

我正在尝试执行 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 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);
  });
})()

我通常会尝试把事情分开。看起来你想保存一个文件,所以我考虑到了这一点。我把每一个请求都放在它自己的承诺中。我认为您不需要 Ftp.raw。我不确定 Ftp 是节点库还是另一个库的 var 名称。

const util = require("util");
const fs = require("fs");

const fsOpen = util.promisify(fs.open);
const fsWriteFile = util.promisify(fs.writeFile);
const fsClose = util.promisify(fs.close);

async function saveDocumentAndListDirectoryFiles() {
  let documentData;
  let fileToCreate;
  let listDirectoryFiles

  //We get the document
  try {
    documentData = await getDocument();
  } catch (error) {
    console.log(error);
    return;
  }

  // Open the file for writing
  try {
    fileToCreate = await fsOpen("./document.txt", "wx");
  } catch (err) {
    reject("Could not create new file, it may already exist");
    return;
  }

  // Write the new data to the file
  try {
    await fsWriteFile(fileToCreate, documentData);
  } catch (err) {
    reject("Error writing to new file");
    return;
  }

  // Close the file
  try {
    await fsClose(fileToCreate);
  } catch (err) {
    reject("Error closing new file");
    return;
  }

  // List all files in a given directory
  try {
    listDirectoryFiles = await listFiles("/");
  } catch (error) {
    console.log("Error: No files could be found");
    return;
  }

  console.log(
    "Contents of tmp file above, after unlinking: ",
    listDirectoryFiles
  );
};

// Get a document
function getDocument() {
  return new Promise(async function(resolve, reject) {
    try {
      await Ftp.get("document.txt", "document.txt");
      resolve();
    } catch (err) {
      reject("There was an error retrieving the file.");
      return;
    }
  });
};

// List all the items in a directory
function listFiles(dir) {
  return new Promise(async function(resolve, reject) {
    try {
      await fs.readdir(dir, function(err, data) {
        resolve(data);
      });
    } catch (err) {
      reject("Unable to locate any files");
      return;
    }
  });
};

saveDocumentAndListDirectoryFiles();