为什么我的 Async Await 在 NodeJS 中不起作用?

Why is my Async Await not working in NodeJS?

尝试在 NodeJS 中执行基本 async/await,但它仍然出现故障。

我正在尝试的代码 运行:

var fs = require('fs');
var stringData;

async function find(context) {
  try {
    let text = await readFile('./sql/test.sql', context);
  } catch (e) {
    console.log('Try/Catch Error: ' + e)
  }

  console.log('display')
  console.log('display ' + JSON.stringify(text))
  return
}

async function readFile(file, context) {
  new Promise((resolve) => {
    fs.readFile(file, (error, data) => {
        if (error) {
          throw error;
        }
        stringData = data.toString()
      }),
      (err) => {
        console.log('ERROR: ' + JSON.stringify(err));
      }, () => {
        resolve(1);
      }
  })
};

module.exports.find = find;

当我 运行 以上时,我得到了文本 console.log 的未定义结果。

我希望文本在向下移动到控制台日志之前使用等待来填充。

看起来你没有用从 data.toString(); 得到的结果来解决承诺 您需要添加 resolve(stringData)

PS。在您使用 resolve 的错误处理程序中,您可能应该在那里使用 reject