[翻译]  How to read file with async/await properly?

[CHINESE]  如何正确读取async / await文件?


I cannot figure out how async/await works. I slightly understands it but I can't make it work.

我无法弄清楚async / await是如何工作的。我稍微理解它,但我不能使它工作。

function loadMonoCounter() {
    fs.readFileSync("monolitic.txt", "binary", async function(err, data) {
       return await new Buffer( data);
  });
}

module.exports.read = function() {
  console.log(loadMonoCounter());
};

I know I could use readFileSync, but if I do, I know I'll never understand async/await and I'll just burry the issue.

我知道我可以使用readFileSync,但如果我这样做,我知道我永远不会理解async / await,我只会把问题埋没。

Goal: Call loadMonoCounter() and return the content of a file.

目标:调用loadMonoCounter()并返回文件的内容。

That file is incremented every time incrementMonoCounter() is called (every page load). The file contain the dump of a buffer in binary and is stored on a SSD.

每次调用incrementMonoCounter()(每个页面加载)时,该文件都会递增。该文件包含二进制缓冲区的转储,并存储在SSD中。

No mather what I do, I get an error or undefined in the console.

不管我做什么,我在控制台中收到错误或未定义。

1 个解决方案

#1


34  

To use await/async you need methods that return promises. The core API functions don't do that without wrappers like promisify:

要使用await / async,您需要返回promise的方法。没有像promisify这样的包装器,核心API函数不会这样做:

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

// Convert fs.readFile into Promise version of same    
const readFile = util.promisify(fs.readFile);

async function getStuff() {
  return await readFile('test');
}

// Can't use `await` outside of an async function so you need to chain
// with then()
getStuff().then(data => {
  console.log(data);
})

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.

作为注释,readFileSync不接受回调,它返回数据或抛出异常。您没有获得所需的值,因为您提供的功能被忽略,而您没有捕获实际的返回值。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号