使用基于 Promise 的 readFile 函数读取文件
在这一步中,你将学习如何使用基于 Promise 的readFileSync函数来读取test-promisefy.json文件。
- 将以下代码添加到
index.js文件中:
fs.readFile(textPath, "utf8", (err, contrast) => {
const readFileSync = promisefy(fs.readFile);
readFileSync(textPath, "utf8")
.then((res) => {
console.log(res === contrast); // 这里预期的结果是:true,即 Promise 返回的内容与之前读取的相同。
})
.catch((err) => {});
});
这段代码使用文件路径和编码调用readFileSync函数,然后使用then和catch方法处理 Promise 的成功和失败情况。
- 现在,你的
index.js文件应该如下所示:
const fs = require("fs");
const path = require("path");
const textPath = path.join(__dirname, "/test-promisefy.json");
fs.readFile(textPath, "utf8", (err, contrast) => {
const readFileSync = promisefy(fs.readFile);
readFileSync(textPath, "utf8")
.then((res) => {
console.log(res === contrast); // 这里预期的结果是:true,即 Promise 返回的内容与之前读取的相同。
})
.catch((err) => {});
});
const promisefy = (fn) => {
return (textPath, type) => {
return new Promise((resolve, reject) => {
fn(textPath, type, (err, contrast) => {
if (err) {
reject(err);
} else {
resolve(contrast);
}
});
});
};
};
module.exports = promisefy;
- 在终端中运行
index.js文件:
node index
你应该会看到输出true,这意味着基于 Promise 的readFile函数返回了与原始基于回调的readFile函数相同的内容。
恭喜!你已经成功地将readFile函数转换为基于 Promise 的函数,并使用基于 Promise 的版本读取了文件。