将async/await与util.prosify(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');

改为从fs/promise导入,如下所示:

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

此版本返回您想要使用的promise,然后您不需要手动将readFile包装在promise中。

以下是使用异步/等待的更多方法

编辑:正如@jfriend00在评论中指出的那样,您当然必须使用标准的NodeJS功能和fs.readFile等内置方法。因此,我将下面代码中的fs方法更改为自定义方法,您可以在其中定义自己的promise。

// Create your async function manually
const asyncFn = data => {
// Instead of result, return promise
return new Promise((resolve, reject) => {
// Here we have two methods: resolve and reject.
// To end promise with success, use resolve
// or reject in opposite
//
// Here we do some task that can take time.
// For example purpose we will emulate it with
// setTimeout delay of 3 sec.
setTimeout(() => {
// After some processing time we done
// and can resolve promise
resolve(`Task completed! Result is ${data * data}`);
}, 3000);
});
}
// Create function from which we will
// call our asyncFn in chain way
const myFunct = () => {
console.log(`myFunct: started...`);
// We will call rf with chain methods
asyncFn(2)
// chain error handler
.catch(error => console.log(error))
// chain result handler
.then(data => console.log(`myFunct: log from chain call: ${data}`));
// Chain call will continue execution
// here without pause
console.log(`myFunct: Continue process while chain task still working.`);
}
// Create ASYNC function to use it
// with await
const myFunct2 = async () => {
console.log(`myFunct2: started...`);
// Read file and wait for result
const data = await asyncFn(3);
// Use your result inline after promise resolved
console.log(`myFunct2: log from async call: ${data}`);
console.log(`myFunct2: continue process after async task completed.`);
}
// Run myFunct
myFunct();
myFunct2();

最新更新