首页 > 解决方案 > 将 async/await 与 util.promisify(fs.readFile) 一起使用?

问题描述

我正在尝试学习 async/await,您的反馈会很有帮助。

我只是将 fs.readFile() 用作尚未使用 Promises 和 async/await 进行现代化改造的函数的具体示例。

(我知道 fs.readFileSync() 但我想学习这些概念。)

下面的模式是一个好的模式吗?有什么问题吗?

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

//promisify converts fs.readFile to a Promised version
const readFilePr = util.promisify(fs.readFile); //returns a Promise which can then be used in async await

async function getFileAsync(filename) {
    try {
        const contents = await readFilePr(filename, 'utf-8'); //put the resolved results of readFilePr into contents
        console.log('✔️ ', filename, 'is successfully read: ', contents);
    }
    catch (err){ //if readFilePr returns errors, we catch it here
        console.error('⛔ We could not read', filename)
        console.error('⛔ This is the error: ', err); 
    }
}

getFileAsync('abc.txt');

标签: node.js

解决方案


而是从 fs/promises 导入,如下所示:

const { readFile } = require('fs/promises')

此版本返回您要使用的承诺,然后您无需手动将 readFile 包装在承诺中。


推荐阅读