Return 似乎没有在等待 javascript

Return doesn't seem to be awaiting javascript

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

const readFile = util.promisify(fs.readFile)

const buildMap = async () => {
  let map = await readFile(process.argv[2], { encoding: 'utf-8' })
  console.log(map) // Returns the right result
  return map // Returns `Promise { <pending> }`
}

const game = buildMap()
console.log(game)

为什么在上面的代码中,特别是

let map = await readFile(process.argv[2], { encoding: 'utf-8' })
console.log(map) // Returns the right result
return map // Returns Promise { <pending> }

return return 的 Promise 未决,即使它上面的行有正确的结果?我该如何改变它才能做到这一点?

提前致谢,对于写得不好的问题深表歉意...(编写精心制定的 SO 问题不是我的强项之一)

async 函数总是 return 承诺(即使它们的操作是完全同步的)。您必须根据调用结果调用 .then

buildMap().then((game) => {
  // do stuff with game
  console.log(game);
});

请注意,您不能仅将其与

之类的东西一起使用
const game = await buildMap();

因为您不能 await 在顶层 - 您只能 await 在异步函数内部。