回报的承诺和内容(可以很多)

我是node.js的新手,试图绕过诺言。 我正在尝试从文件中读取内容,返回一个承诺和文件的内容。 我到目前为止能够阅读文件的内容,并在我的控制台上打印,并返回一个承诺。 我也想返回文件的内容。

这是我的代码到目前为止。

function() { return fs.exists(listFile).then(function (exists) { if(exists) { return fs.readFile(listFile).then(function(response) { console.log(response.toString()); }).catch(function(error) { console.error('failed to read from the file', error); }); } }).catch(function(err) { console.error('Error checking existence', err) }); }; 

fs.readFile(listFile)返回一个promise。 这就是为什么你可以链接“.then()”方法。 目前没有什么可以回报的。 此外,它将返回到您在第二行传递给“.then”的callback函数。

要访问文件的内容,您需要调用另一个函数,将文件的内容直接打印到控制台。

 function() { return fs.exists(listFile).then(function (exists) { if(exists) { fs.readFile(listFile).then(function(response) { console.log(response.toString()); handleFileContents(response.toString()); }).catch(function(error) { console.error('failed to read from the file', error); }); } }).catch(function(err) { console.error('Error checking existence', err) }); }; function handleFileContents(content) { // ... handling here } 

你不能自己return文件的内容,它们是asynchronous检索的。 你所能做的只是返回一个承诺的内容:

 function readExistingFile(listFile) { return fs.exists(listFile).then(function (exists) { if (exists) { return fs.readFile(listFile).then(function(response) { var contents = response.toString(); console.log(contents); return contents; // ^^^^^^^^^^^^^^^^ }).catch(function(error) { console.error('failed to read from the file', error); return ""; }); } else { return ""; } }).catch(function(err) { console.error('Error checking existence', err) return ""; }); } 

像使用它

 readExistingFile("…").then(function(contentsOrEmpty) { console.log(contentsOrEmpty); }); 

顺便说一句, 使用像你这样的fs.exists是一个反模式 ,它一般不推荐使用。 省略它,只是从一个不存在的文件捕获错误:

 function readExistingFile(listFile) { return fs.readFile(listFile).then(function(response) { return response.toString(); }, function(error) { if (error.code == "ENOENT") { // did not exist // … } else { console.error('failed to read from the file', error); } return ""; }); }