且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用异步/等待正确读取文件?

更新时间:2022-06-09 09:33:04

要使用 await/async 您需要返回承诺的方法.如果没有像 promisify这样的包装器,核心 API 函数就无法做到这一点>:

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.