Завершение FTP-запроса в Async / Await - PullRequest
0 голосов
/ 02 марта 2019

Я пытаюсь выполнить запрос 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);
});

Ответы [ 2 ]

0 голосов
/ 02 марта 2019

Я обычно стараюсь отделить вещи.Похоже, вы хотели сохранить файл, поэтому я создал это с учетом этого.Я помещаю каждый запрос в свое обещание.Я не думаю, что вам нужен Ftp.raw.Я не уверен, является ли Ftp библиотекой узлов или просто именем переменной другой библиотеки.

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();
0 голосов
/ 02 марта 2019

Во-первых, await работает только с обещаниями, и ftp.get явно использует обратный вызов вместо обещания.Таким образом, вам нужно обернуть ftp.get в обещание.

Во-вторых, ваш fs.readdir находится за пределами асинхронной функции, поэтому ожидание не повлияет на него.Если вам нужно, чтобы оно было отложено, то вам нужно, чтобы оно было внутри асинхронной функции после оператора 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);
  });
})()
...