如何正确地使用async

如何正确地使用async

本文介绍了如何正确地使用async/await读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚async/await的工作方式.我对此有些了解,但无法使其正常工作.

I cannot figure out how async/await works. I slightly understands 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 contain 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.

这篇关于如何正确地使用async/await读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:18