返回似乎没有等待javascript

时间:2018-04-29 07:13:02

标签: 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 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> }

返回返回Promise pending,即使它上面的行有正确的结果?我怎么能改变这个呢?

提前致谢并抱歉这个写得不好的问题......(撰写精心设计的SO问题不是我的优点之一)

1 个答案:

答案 0 :(得分:2)

mainClass函数总是返回promises(即使它们的操作完全同步)。您必须在通话结果上拨打async

.then

请注意,您不能只使用

之类的东西来消费它
buildMap().then((game) => {
  // do stuff with game
  console.log(game);
});

因为你不能在顶级const game = await buildMap(); - 你只能在异步函数中await

相关问题