Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 以异步/等待方式包装FTP请求_Javascript_Node.js_Async Await_Es6 Promise - Fatal编程技术网

Javascript 以异步/等待方式包装FTP请求

Javascript 以异步/等待方式包装FTP请求,javascript,node.js,async-await,es6-promise,Javascript,Node.js,Async Await,Es6 Promise,我正在尝试执行FTP请求,等待文件下载完毕,然后关闭FTP模块。完成这两个操作后,列出目录的内容。目前,它正朝着相反的方向努力 我已经用async包装了它们,并在FTP前面加了wait。但目录列表将首先被记录。可以在异步函数中发现错误吗 (async function () { await Ftp.get("document.txt", "document.txt", err => { if (err) { return console.error("There w

我正在尝试执行FTP请求,等待文件下载完毕,然后关闭FTP模块。完成这两个操作后,列出目录的内容。目前,它正朝着相反的方向努力

我已经用async包装了它们,并在FTP前面加了wait。但目录列表将首先被记录。可以在异步函数中发现错误吗

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

首先,wait只适用于承诺,ftp.get显然使用回调而不是承诺。所以你必须打包ftp,承诺一下

其次,您的fs.readdir在异步函数之外,因此它不会受到等待的影响。如果需要将其延迟,则需要将其放在异步函数中,在wait语句之后

所以把这些放在一起,看起来像这样:

(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();

这看起来很好,但是我可以把readdir放在异步函数之外吗?你想这样做的原因是什么?在这个FTP函数之后,我需要加载更多的代码。我不想把它都包装在一个异步函数中。你有没有可能关注一下我想要使用的主FTP程序以及它的问题?我不确定用异步函数包装它的犹豫是什么。如果要让代码等待ftp.get完成,您的选项是:1)将代码放在异步函数中,然后等待承诺;2)将代码放在回调函数中,并将该函数显式传递到
中。然后
回调承诺;3)放弃承诺,将代码放在ftp.get的回调函数中。我建议使用#1,因为它最容易阅读。不要将其赋值给未声明的(全局?)变量,而是使用函数声明。啊!好球。:)