Javascript 返回不';我好像没在等你 const fs=require('fs')) const util=require('util') const readFile=util.promisify(fs.readFile) const buildMap=async()=>{ 让map=wait readFile(process.argv[2],{encoding:'utf-8'}) console.log(map)//返回正确的结果 返回映射//返回`Promise{}` } const game=buildMap() 控制台日志(游戏)

Javascript 返回不';我好像没在等你 const fs=require('fs')) const util=require('util') const readFile=util.promisify(fs.readFile) const buildMap=async()=>{ 让map=wait readFile(process.argv[2],{encoding:'utf-8'}) console.log(map)//返回正确的结果 返回映射//返回`Promise{}` } const game=buildMap() 控制台日志(游戏),javascript,node.js,async-await,es6-promise,ecmascript-2017,Javascript,Node.js,Async Await,Es6 Promise,Ecmascript 2017,为什么在上面的代码中,特别是 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

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

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=wait readFile(process.argv[2],{encoding:'utf-8'})
console.log(map)//返回正确的结果
返回映射//返回承诺{}
即使上面的行有正确的结果,返回仍然返回Promise pending?我怎样才能改变它呢


提前谢谢,对于写得不好的问题,我深表歉意。。。(我的强项之一不是写一个很好的公式化的问题)

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

let map = await readFile(process.argv[2], { encoding: 'utf-8' })
console.log(map) // Returns the right result
return map // Returns Promise { <pending> }
请注意,您不能仅用类似的东西来消费它

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

因为您不能在顶层
等待
——您只能在异步函数内部
等待

您可以将此添加为答案吗please@CertainPerformance请不要在评论中回答问题。不花时间回复会让回复的人看起来像是抄袭了你的评论——就好像他们根本不知道问题的答案一样@好的,我把它变成了一个答案。我注意到其他人经常在评论中回答一些很小的问题,当我发布一个真实的答案(对于一些琐碎但没有错别字的问题)而不是一条评论时,它有时会吸引反对票。@CertainPerformance感谢您发布了答案。其他一些人以在评论中回答问题而闻名,但年纪太大,无法纠正:-)吸引否决票有其自身的风险标准-否决票可能意味着答案可能会更重要!哦,谢谢,我错过了“顶级
wait
”的要点。我在谷歌上搜索了一篇关于这件事的文章:
const game = await buildMap();