如何使用异步/等待正确读取文件? [英] How to read file with async/await properly?
问题描述
我无法弄清楚 async
/await
是如何工作的.我有点明白,但我不能让它工作.
I cannot figure out how async
/await
works. I slightly understand it but I can't make it work.
function loadMonoCounter() {
fs.readFileSync("monolitic.txt", "binary", async function(err, data) {
return await new Buffer( data);
});
}
module.exports.read = function() {
console.log(loadMonoCounter());
};
我知道,我可以使用 readFileSync
,但是如果我这样做了,我知道我永远不会理解 async
/await
并且我'只会把问题埋起来.
I know, I could use readFileSync
, but if I do, I know I'll never understand async
/await
and I'll just bury the issue.
目标:调用loadMonoCounter()
并返回文件内容.
Goal: Call loadMonoCounter()
and return the content of a file.
每次调用 incrementMonoCounter()
时(每次加载页面),该文件都会递增.该文件包含二进制缓冲区的转储,并存储在 SSD 上.
That file is incremented every time incrementMonoCounter()
is called (every page load). The file contains the dump of a buffer in binary and is stored on a SSD.
无论我做什么,我都会在控制台中收到错误或 undefined
.
No matter what I do, I get an error or undefined
in the console.
推荐答案
要使用 await
/async
您需要返回承诺的方法.如果没有像 promisify
:
To use await
/async
you need methods that return promises. The core API functions don't do that without wrappers like promisify
:
const fs = require('fs');
const util = require('util');
// Convert fs.readFile into Promise version of same
const readFile = util.promisify(fs.readFile);
function getStuff() {
return readFile('test');
}
// Can't use `await` outside of an async function so you need to chain
// with then()
getStuff().then(data => {
console.log(data);
})
注意,readFileSync
不接受回调,它返回数据或抛出异常.你没有得到你想要的值,因为你提供的函数被忽略了,你没有捕获实际的返回值.
As a note, readFileSync
does not take a callback, it returns the data or throws an exception. You're not getting the value you want because that function you supply is ignored and you're not capturing the actual return value.
这篇关于如何使用异步/等待正确读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!